#include <iostream>
using namespace std;
class point
{
public:
int x,y;
inline int getX() { return x; }
inline int getY() { return y; }
inline void setX(int v) { x=v; }
inline void setY(int v) { y=v; }
};
point operator+ (point& p1, point& p2)
{
point sum = {p1.x+p2.x, p1.y+p2.y};
return sum;
}
ostream& operator<< (ostream& out, point& p)
{
out<<"("<<p.x<<","<<p.y<<")";
return out;
}
int main()
{
point a={3,5},b={6,7};
cout<<"Sum="<<a+b;
}
以上代码因编译错误而失败:
startingClasses.C:33:17:错误:从'point'类型的右值开始无效初始化'point&amp;'类型的非const引用 COUT&LT;&LT; “总和=” &LT;
但是下面的代码可以运行:
#include <iostream>
using namespace std;
class point
{
public:
int x,y;
inline int getX() { return x; }
inline int getY() { return y; }
inline void setX(int v) { x=v; }
inline void setY(int v) { y=v; }
};
point operator+ (point& p1, point& p2)
{
point sum = {p1.x+p2.x, p1.y+p2.y};
return sum;
}
ostream& operator<< (ostream& out, **const** point& p)
{
out<<"("<<p.x<<","<<p.y<<")";
return out;
}
int main()
{
point a={3,5},b={6,7};
cout<<"Sum="<<a+b;
}
在代码中添加const
使其正常工作......仍然不明白。