diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ac3f262..af57750 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -11,3 +11,4 @@ add_executable(exceptions exceptions.cc) add_executable(HeapMemory HeapMemory.cc) add_executable(AbstractClasses AbstractClasses.cc) add_executable(vector vector.cc) +add_executable(Vector2 Vector2.cc) diff --git a/src/Vector2.cc b/src/Vector2.cc new file mode 100644 index 0000000..a7237df --- /dev/null +++ b/src/Vector2.cc @@ -0,0 +1,54 @@ +#include +#include +#include +class Vector2 { +public: + double x; + double y; + + Vector2(double x, double y) + { + this->x = x; + this->y = y; + } + + Vector2 operator+(const Vector2& vec) + { + return Vector2(x + vec.x, y + vec.y); + } + + Vector2 operator-(const Vector2& vec) + { + return Vector2(x - vec.x, y - vec.y); + } + + Vector2 operator*(const Vector2& vec) + { + return Vector2(x * vec.x, y * vec.y); + } + + Vector2 operator/(const Vector2& vec) + { + return Vector2(x / vec.x, y / vec.y); + } + + constexpr std::string to_string() { + return std::format("<{},{}>",x,y); + } +}; + +int main() +{ + Vector2 position(5, 10); + Vector2 offset(10, 5); + + Vector2 destination = position + offset; + Vector2 negativeDestination = position - offset; + Vector2 multipledDestination = position * offset; + Vector2 dividedDestination = position / offset; + + std::cout << std::format("positive destination: {}", destination.to_string()) << std::endl; + std::cout << std::format("negative destination: {}", negativeDestination.to_string()) << std::endl; + std::cout << std::format("multipled destination: {}", multipledDestination.to_string()) << std::endl; + std::cout << std::format("divided destination: {}", dividedDestination.to_string()) << std::endl; +} diff --git a/src/vector.cc b/src/vector.cc index 35c776f..ec2d1e3 100644 --- a/src/vector.cc +++ b/src/vector.cc @@ -1,6 +1,6 @@ +#include #include #include -#include class Vector { public: @@ -18,6 +18,26 @@ public: delete[] elem; } + Vector(const Vector& a) + : elem(new double[a.sz]) + , sz { a.sz } + { + for (int i = 0; i!=sz;++i) { + elem[i] = a.elem[i]; + } + } + + Vector& operator=(const Vector& a) { + double* p = new double[a.sz]; + for (int i =0; i!=sz; ++i) { + p[i] = a.elem[i]; + } + delete[] elem; + elem = p; + sz = a.sz; + return *this; + } + double& operator[](int i) { if (i < 0 || i > size() - 1) {