Reputation: 11
I've searched stackoverflow a bit and found some topics similar to what I am doing. However, I just do not understand yet the probably very simple errors I made.
Can you please help me out? As you can see I make really basic mistakes.
The function is for practice purposes only. I want to have a class for points with x
, y
coordinates in double data type, these are privates.
To practice operator overloading/member function based operator access to privates, I wrote the following code.
In the end, I just want to print out the results of the addition of each of the coordinates x
and y
of two points.
What are the mistakes that I am making?
Thank you in advance for any hints.
#include <stdio.h>
#include <iostream>
class point{
public:
// this operator adds a point "p2" to the point of class "point"
// OVERLOADING BINARY + USING A MEMBER FUNCTION:
point operator+(point p){ // n is the 2nd number in the addition
return point(x+p.x, y+p.y); // equals (this->x+p2.x, ...)
}
// private numbers
private:
//declaration and initialization of x and y:
double x=1.1,y=2.2;
};
int main()
{
// Create two new points:
point *p1 = new point ();
point *p2 = new point ();
cout << "The result of the addition is: " << (*p1+*p2);
return 0;
}
Currently the error I get is:
In member function ‘point point::operator+(point)’: main.cpp:16:38:
error: no matching function for call to ‘point::point(double, double)’
return point(x+p.x, y+p.y); // equals (this->x+p2.x, ...)
Upvotes: 0
Views: 608
Reputation: 11
Like churill pointed out, you missed implementing two things:
First you need to implement a constructor for your point class that takes 2 doubles:
point(double x, double y)
: x(x), y(y)
{}
The above constructor is using initializer lists and does the same as this:
point(double x, double y) {
this.x = x;
this.y = y;
}
and don't forget to implement the default constructor again since otherwise C++ will not find it anymore and your code will fail to compile
point() {}
Second You need to overwrite the "<<" operator which will allow you to cout your point object:
friend ostream& operator<<(ostream& os, const point& p) {
os << "(" << p.x << ',' << p.y << ')'; // will output (x,y)
return os;
}
if you put all the above in your point class as public it should compile without a problem
Upvotes: 1