Create a class vector with array a[n] and calculate v2=v1*5 and v3=4*v1. Use friend function in overloading operators.
#include<bits/stdc++.h>
using namespace std;
class Vector
{ int x,y,z;
public:
Vector(int x, int y, int z)
{
// Constructor
this->x = x;
this->y = y;
this->z = z;
}
Vector(const Vector &p1)
{
x = p1.x;
y = p1.y;
z = p1.z;
}
friend Vector operator *(Vector v2,int n)
{
int x1,y1,z1;
x1=v2.x*n;
y1=v2.y*n;
z1=v2.z*n;
return Vector(x1,y1,z1);
}
friend Vector operator *(int n, Vector v2)
{
int x1,y1,z1;
x1=v2.x*n;
y1=v2.y*n;
z1=v2.z*n;
return Vector(x1,y1,z1);
}
friend ostream& operator<<(ostream& out, const Vector& v)
{
out << v.x << "i ";
if (v.y >= 0)
out << "+ ";
out << v.y << "j ";
if (v.z >= 0)
out << "+ ";
out << v.z << "k" << endl;
return out;
}
};
int main()
{
int i,j,k,n;
cout<<"Enter the elements i,j and k for vector ";
cin>>i>>j>>k;
Vector V1(i,j,k);
cout<<"Enter the value of n ";
cin>>n;
Vector V3=(V1*n);
cout<<"Multiplication by n "<<V3;
cout<<"Enter the elements i,j and k for vector ";
cin>>i>>j>>k;
Vector V2(i,j,k);
cout<<"Enter the value of n ";
cin>>n;
Vector V4=(n*V2);
cout<<"Multiplication by n "<<V4;
}
Comments
Leave a comment