Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef EDYA_P3_VECTOR2D_H
- #define EDYA_P3_VECTOR2D_H
- #include <iostream>
- #include <cmath>
- /**
- * FLOAT | DOUBLE
- * @tparam T
- */
- template<class T>
- class vec2d {
- public:
- vec2d(T x = 0, T y = 0) {
- this->x = x;
- this->y = y;
- }
- virtual ~vec2d() {
- std::cout << "\n~vec2d" << *this;
- }
- T getX() { return this->x; }
- T getY() { return this->y; }
- void setX(T x) { this->x = x; }
- void setY(T y) { this->y = y; }
- T mag() {
- return sqrt(x * x + y * y);
- }
- T dot(const vec2d &v) {
- return (this->x) * (v.x) + (this->y) * (v.y);
- }
- T cross(const vec2d &v) {
- return (this->x) * (v.y) - (this->y) * (v.x);
- }
- vec2d operator+(const vec2d &v1) {
- return vec2d(v1.x + x, v1.y + y);
- }
- vec2d operator-(const vec2d &v1) {
- return vec2d(x - v1.x, y - v1.y);
- }
- vec2d &operator+=(const vec2d &vec_sum) {
- this->x += vec_sum.x;
- this->y += vec_sum.y;
- return *this;
- }
- vec2d &operator-=(const vec2d &vec_res) {
- this->x -= vec_res.x;
- this->y -= vec_res.y;
- return *this;
- }
- vec2d &operator/=(T i) {
- i = i == 0 ? 1 : i;
- this->x /= i;
- this->y /= i;
- return *this;
- }
- vec2d operator/(T i) {
- vec2d rta;
- rta.x = this->x / i;
- rta.y = this->y / i;
- return rta;
- }
- vec2d operator*(T i) {
- vec2d rta;
- rta.x = this->x * i;
- rta.y = this->y * i;
- return rta;
- }
- vec2d &operator*=(const T &v) {
- this->x *= v;
- this->y *= v;
- return *this;
- }
- friend std::ostream &operator<<(std::ostream &out, const vec2d &vec) {
- return out << "(" << vec.x << ", " << vec.y << ")";
- }
- bool operator==(const vec2d &rhs) {
- return x == rhs.x && y == rhs.y;
- }
- bool operator!=(const vec2d &rhs) {
- return !(*this == rhs);
- }
- private:
- T x, y;
- };
- typedef vec2d<float> vf2d;
- typedef vec2d<double> vd2d;
- typedef vec2d<int> vi2d;
- void test_vector() {
- vf2d w(1.0, 4.0);
- vd2d p(1.0, 4.0);
- vec2d<double> i(1.0, 4.0);
- vec2d<double> j(2.0, 3.0);
- vec2d<double> k = i + j - i;
- std::cout << std::endl << i;
- std::cout << std::endl << j;
- std::cout << std::endl << k;
- k = k * 4.0;
- std::cout << std::endl << k;
- k = k / 2;
- std::cout << std::endl << k;
- k *= 4.0;
- std::cout << std::endl << k;
- k /= 2;
- std::cout << std::endl << k;
- std::cout << std::endl << vec2d<double>(1, 1).mag();
- std::cout << std::endl << vec2d<double>(3, 4).mag();
- std::cout << std::endl << i << " x " << j << " = " << i.cross(j);
- std::cout << std::endl << i << " . " << j << " = " << i.dot(j);
- std::cout << std::endl;
- }
- #endif //EDYA_P3_VECTOR2D_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement