C++/Operator Overloading
Expert: Prince M. Premnath - 10/25/2009
Questioncould u pls help mi,i dun knw which part of the code is wrong.i'm realli appericated for all the help frm u.
tis is the result i gt wen i compile the program:
Enter first vector, format a b c: 5,6,7
Enter second vector, format a b c:
Addition A+B = (10,4587152,4587080)
the result i gt is nt correct.i onli gt to enter the first vector,i cnnot gt to enter the second vector.could u pls tell mi wat i should do to correct it.
the result i gt should be tis:
example result:
Inputs: A(5,6,7)
B(3,8,2)
Outputs: A + B (8,14,9)
code:
#include <iostream>
using namespace std;
class myVector
{
int x,y,z;
public:
myVector() { x = y = z = 0; }
myVector(int xPart, int yPart, int zPart) { x = xPart; y = yPart; z = zPart; }
myVector operator+(const myVector &mv)const;
friend ostream& operator<<(ostream& out, const myVector& vec);
};
myVector myVector::operator +(const myVector &mv)const //Addition
{
myVector result;
result.x = x + mv.x;
result.y = y + mv.y;
result.z = z + mv.z;
return result;
}
ostream& operator<<(ostream& out, const myVector& vec)
{
out << '(' << vec.x << ',' << vec.y << ',' << vec.z << ')';
return out;
}
//main program to test the class
int main()
{
myVector v1(1,2,3);
myVector v2(3,2,1);
myVector sum = v1 + v2;
int x,y,z;
cout << "Enter first vector, format a b c: ";
cin >> x >> y >> z;
cout << endl;
myVector A(x,y,z);
cout << "Enter second vector, format a b c: ";
cin >> x >> y >> z;
cout << endl;
myVector B(x,y,z);
myVector C = A + B;
cout<<"Addition A+B = "<< C << endl;
return 0;
}
Answer
Hi dear angeline!
Ive tested your programme , i don't find any bugs , and even more its running good , ive attached screen shot of the execution.
Note: If you still feel that your prog suffering from bugs, please be specific about the bug :-)
Thanks and Regards
Prince M. Premnath