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

Popular posts from this blog

153: Write a program to read an amount (integer value) and break the amount into smallest possible number of bank notes. Note: The possible banknotes are 500, 100, 50, 20, 10, 5, 2, and 1

206: Write a program to create a class named "Circle" which has the property "radius". Define functions to calculate the area and circumference of the circle.

221: // In Task 2, we discussed multilevel inheritance with parameterized constructors for Student, UndergraduateStudent, and GraduateStudent classes in a university management system. Can you explain the advantages of using multilevel inheritance with specific details about the functions and data members in these classes? How were the parameterized constructors (e.g., setting student name, age, and ID) used to ensure that each class in the hierarchy correctly initializes its properties, such as creating an UndergraduateStudent named "John," aged 20, with a student ID of 12345