Displaying result of addition of vectors
May 28, 2014 at 2:40pm May 28, 2014 at 2:40pm UTC
Hello everybody!
I'm trying to display the result of addition of vectors. But Builder shows the error after compilation (line 29). What should I change for in my code in order to find the problem?
Thanks in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
class CVector2D {
public :
CVector2D(double x0 = 0, double y0 = 0)
:x(x0), y(y0)
{
}
double x, y;
CVector2D const operator +(CVector2D const & vector2)const {
return CVector2D(x + vector2.x, y + vector2.y);
}
};
using namespace std;
int main()
{
CVector2D a(3.0, 5.8);
CVector2D b(7.3, 8.8);
CVector2D c = a + b + CVector2D(3, 9);
cout << "Sum is equal " << c << endl;
getch();
return 0;
}
Error (line 29):
[C++ Error] 5.cpp(27): E2094 'operator<<' not implemented in type 'ostream' for arguments of type 'CVector2D'
Last edited on May 28, 2014 at 2:42pm May 28, 2014 at 2:42pm UTC
May 28, 2014 at 3:12pm May 28, 2014 at 3:12pm UTC
I think your problem is that std::cout doesn't recognize your CVector2D class. So you use the << operator for "Sum is equal", which it recognizes as a string, but then << c confuses it. If you added the x and y components of your vector in the class, you could do:
cout << "Sum is equal " << c.x << " " << c.y << endl;
May 28, 2014 at 3:44pm May 28, 2014 at 3:44pm UTC
It's required to display the sum of vectors.
If I attend <stdio.h> and use
printf("Sum is equal " , c);
The Output
without value.
May 28, 2014 at 4:02pm May 28, 2014 at 4:02pm UTC
ostream doesn't know how to output a CVector2D object. You need to overload the << operator in your class.
1 2 3 4
friend ostream & operator << (ostream & os, const CVector2D & cv)
{ os << cv.x << ',' << cv.y; // Or however you want to format it
return os;
}
Last edited on May 28, 2014 at 4:02pm May 28, 2014 at 4:02pm UTC
May 28, 2014 at 4:15pm May 28, 2014 at 4:15pm UTC
Hey AbstractionAnon, first off thank you for your insight, your explanation makes it more clear to me.
Thanks again!
Topic archived. No new replies allowed.