【发布时间】:2021-04-21 05:16:42
【问题描述】:
我搜索了一下stackoverflow,发现了一些与我正在做的事情相似的主题。但是,我只是不明白我犯的可能非常简单的错误。
你能帮帮我吗?如您所见,我犯了非常基本的错误。
该功能仅用于练习目的。我想为带有x、y 双数据类型坐标的点创建一个类,这些是私有的。
为了练习运算符重载/基于成员函数的运算符对私有的访问,我编写了以下代码。
最后,我只想打印出两点坐标x和y的相加结果。
我犯了什么错误?
提前感谢您的任何提示。
#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;
}
目前我得到的错误是:
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, ...)
【问题讨论】:
-
这个错误基本上告诉你
point没有一个需要2个双精度的构造函数。这是真的。operator<<也没有超载打印point。编译器不会为你做魔法;)
标签: c++ class overloading private operator-keyword