C++程序的输出与预期不同的原因是什么?

What's the reason for different output than expected for C++ program?

本文关键字:是什么 程序 输出 C++      更新时间:2023-10-16

我遇到了一个程序,它给出的输出与我预期的不同。可能是什么原因?

程序:

#include <iostream>
using namespace std;
//Class A
class A
{
    int x,y;
    public:
    //constructor
    A(int X,int Y):x(X),y(Y)
    {
    }
    A SetX(int X)
    {
        x = X;
        return *this;
    }
    A SetY(int Y)
    {
        y=Y;
        return *this;
    }
    void print()
    {
        cout << x << " " << y;
    }
};
int main()
{
    A a(5, 5);
    a.SetX(10).SetY(20);//???
    a.print();
}

从这里可以看出,创建的值为 5,5 的 a,然后分别用值 10 和 20 调用 SetX(( 和 SetY((。在这里,我希望 print(( 将输出显示为 10, 20。但令人惊讶的是,输出是 10,5。正在发生的事情是背景?感谢任何帮助?

您的A SetX(int X)返回对象的副本,因此当您执行a.SetX(10).SetY(20);时,.SetY正在该副本上运行 - 然后被销毁。

您希望将函数签名更改为 A& SetX(int X);,以便返回对原始对象的引用而不是副本。