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

215: Create a C++ program that uses single inheritance to model a simple shape hierarchy. Implement a base class "Shape" with a virtual function "printArea." Derive classes "Rectangle" and "Triangle" from "Shape" and override the "printArea" function to calculate and display their respective areas.

42: ***(Syntax)*** Calculating number of characters and spaces in a string 1- Make a program to calculate the number of characters in a string 2- Modify this and also tell how many spaces are there in that sentence

96: ***(Syntax)*** Functions and Global Variables