c++ - 在 C++ 中,为什么使用或不使用引用作为结果值会得到不同的结果?

标签 c++ c++11 reference

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/

相关文章:

java - 在 Java 类中重新分配 `this`

c - 递归函数在参数不为 NULL 时传递 NULL 指针

python - 将 Eigen 库与 cppyy 一起使用

c++ - 将类模板推迟到其构造函数

c++ - 重载运算符(operator) body 的奥秘

c++ - 在未命名命名空间内使用外部链接初始化变量

c++ - 可变参数模板类的部分特化是否应该支持非可变参数特化

c++ - Sqlite线程设计

c++ - 如何计算两个多重集的就地集差?

c++ - 绑定(bind)类型为 T&& 的左值表达式