211: Create a class to represent a mathematical vector with private data members for its components. Define constant objects and constant member functions to perform vector addition, subtraction, and scalar multiplication. Implement getter and setter functions for the vector components
// Create a class to represent a mathematical vector with private data members for
// its components. Define constant objects and constant member functions to
// perform vector addition, subtraction, and scalar multiplication. Implement
// getter and setter functions for the vector components
#include <iostream>
using namespace std;
class Vector
{
private:
float X;
float Y;
float Z;
public:
// constructors
Vector() : X(0), Y(0), Z(0) {}
Vector(float x = 0, float y = 0, float z = 0) : X(x), Y(y), Z(z) {}
void printVector(string x) const { cout << x << '(' << X << ", " << Y << ", " << Z << ')' << endl; }
// overloaded operators
Vector operator+(const Vector &second) const;
Vector operator-(const Vector &second) const;
Vector operator*(const float &second) const;
};
Vector Vector ::operator+(const Vector &second) const { return Vector(X + second.X, Y + second.Y, Z + second.Z); }
Vector Vector ::operator-(const Vector &second) const { return Vector(X - second.X, Y - second.Y, Z - second.Z); }
Vector Vector ::operator*(const float &second) const { return Vector(X * second, Y * second, Z * second); }
int main()
{
const Vector vec1(1, 2, 3), vec2(4, 5, 6);
const int scalar = 5;
vec1.printVector("Vector 1: ");
vec2.printVector("Vector 2: ");
Vector sum = vec1 + vec2;
sum.printVector("Resultant vector after vector sum: ");
Vector diff = vec1 - vec2;
diff.printVector("Resultant vector after vector difference: ");
Vector multiplication = vec1 * scalar;
multiplication.printVector("Resultant vector after vector multiplication: ");
return 0;
}
Comments
Post a Comment