在C 中,为什么使用或不作为结果值获得不同的结果

In C++, why do I get different results using or not reference as result value?

本文关键字:结果 不作为 为什么      更新时间:2023-10-16
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.9532e-310),而第二个输出是正确的(x:1 y:1)。

以及为什么通过在后收入操作员的返回值结束时删除&来解决此问题?

当您返回对本地变量的引用时,使用该引用是未定义的行为。

您的编译器应该警告您。如果不是这样,请提高编译器警告级别,并注意警告。

point& operator++()
point operator++(int)

是正确的返回值。

您的其余代码看起来都很好。

我将删除using namespace std;,然后将++的实现更改为:

    ++x;
    ++y;
    return *this;