C++/c++
Expert: Eddie - 10/24/2009
Questioncould u pls help mi,i realli need your help.i am trying to do a simple addition of using class vector.i hope u could guide mi.i'm nt sure whether i'm doing it right anot.i will be so appericated for all the help frm u.
example:A vector can be represented in Cartesian coordinates (a, b, c).
Suppose vector X is (a1, b1, c1) and Y is (a2, b2, c2).
Addition:X + Y = (a1+a2, b1+b2, c1+c2).
example result:
Inputs
A(5,6,7)
B(3,8,2)
Outputs A + B (8,14,9)
code:
class myVector
{
int x,y,z;
public:
myVector operator+(const myVector &mv)const;
};
myVector myVector::operator +(const myVector &mv)const //Addition
{
myVector mv;
mv.x = x + mv.x;
mv.y = y + mv.y;
mv.z = z + mv.z;
return mv;
}
//main program to test the class
int main()
{
myVector A,B,C;
cout << "Enter first vector, format (a,b,c): ";
cin >> A;
cout << "Enter second vector, format (a,b,c): ";
cin >> B;
C = A + B;
cout<<"Addition A+B = "<< C << endl;
return 0;
}
AnswerHello lisa, thank you for the question.
You're actually very close. You want to modify the class on the left side of the operator though. Try this:
void myVector::operator +(const myVector &mv)
{
this->x += mv.x;
this->y += mv.y;
this->z += mv.z;
}
If you want to be able to print the myVector class, you also need to overload the << operator:
ostream& myVector::operator << (const ostream &o) const;
{
o << this->x << endl;
o << this->y << endl;
o << this->z << endl;
return o;
}
That should have you fixed up and ready to go. Let me know if it doesn't work. I haven't overloaded a << operator on a class in a while.
I hope this information was helpful.
- Eddie