class point
{
private:
double x,y;
public:
point(double x=0.0, double y=0.0)
{
this->x=x;
this->y=y;
}
point operator++()
{
this->x=this->x+1.0;
this->y=this->y+1.0;
return *this;
}
point& operator++(int)
{
point p=point(this->x, this->y);
++(*this);
return p;
}
ostream& operator<< (ostream& o)
{
o << "X: " << this->x << endl << "Y: " << this->y;
return o;
}
friend ostream& operator<< (ostream& o,point p)
{
o << "X: " << p.x << endl << "Y: " << p.y;
return o;
}
};
int main()
{
point p = point();
p++ << cout << endl; // first output
cout << p++ << endl;// second output
}
我不明白为什么第一个输出不正确 (X: 6.95333e-310 Y: 6.95322e-310),而第二个输出正确 (X: 1 Y: 1)。
以及为什么去掉后自增运算符返回值末尾的&
就解决了这个问题?
最佳答案
当您返回对局部变量的引用时,使用该引用是未定义的行为。
你的编译器应该警告你。如果不是,请提高编译器警告级别,并注意警告。
point& operator++()
point operator++(int)
是正确的返回值。
您的其余代码看起来没问题。
我会删除 using namespace std;
,并将 ++
的实现更改为:
++x;
++y;
return *this;
关于c++ - 在 C++ 中,为什么使用或不使用引用作为结果值会得到不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45988954/