add a Vector2 class

this is a basic implementation of a Vector2 class (a 2D Vector) with
math operator support by overloading the math operators.
This commit is contained in:
Fries 2023-06-22 21:31:19 -07:00
parent 9ee12a7aba
commit 678b854b74
3 changed files with 76 additions and 1 deletions

View file

@ -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)

54
src/Vector2.cc Normal file
View file

@ -0,0 +1,54 @@
#include <format>
#include <iostream>
#include <string>
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;
}

View file

@ -1,6 +1,6 @@
#include <format>
#include <iostream>
#include <stdexcept>
#include <format>
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) {