I'm learning C++, and I have a question about print class type property.
I'm trying to get Point(x, y)
's position, and print it.
Getting position is perfectly work as I thought, but printing does not.
I think it should work, but it doesn't, maybe I am missing something.
Should I cast it to any other value type which could print out?
so I just tried cout << "The position is: " << p1.getPosition();
and I got an error:
prog.cc:29:7: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream'} and 'Point')
29 | cout << p1.getPosition();
| ~~~~ ^~ ~~~~~~~~~~~~~~~~
| | |
| | Point
| std::ostream {aka std::basic_ostream}
Here's my code.
#include <iostream>
using namespace std;
class Point{
double x;
double y;
public:
Point getPosition();
void setPosition(double x_, double y_);
Point operator+(const Point& p);
Point(double x_, double y_)
{
x = x_;
y = y_;
}
};
Point Point::getPosition(){ return Point(x, y); }
void Point::setPosition(double x, double y){ x = this->x; y = this->y; }
Point Point::operator+(const Point& p)
{
return Point((x+p.x), (y+p.y));
}
int main(void)
{
Point p1(5.0, 5.0);
cout << "The position is: " << p1.getPosition() << endl; //error occured
return 0;
}
Thanks you for your help :)