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

时间:2019-04-20 14:46:22

标签: c++

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

程序:

#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。背景是怎么回事?感谢您的帮助吗?

1 个答案:

答案 0 :(得分:2)

您的<?xml version='1.0' encoding='utf-8'?> <tomcat-users xmlns="http://tomcat.apache.org/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd" version="1.0"> <role rolename="tomcat"/> <role rolename="manager-gui"/> <user username="tomcat" password="tomcat" roles="tomcat"/> <user username="both" password="tomcat" roles="tomcat,manager-gui"/> <user username="manager-gui" password="tomcat" roles="manager-gui"/> </tomcat-users> 返回该对象的副本,因此,当您执行A SetX(int X)时,a.SetX(10).SetY(20);在该副本上进行操作-然后将其销毁。

您想要将函数签名更改为.SetY,以便您返回对原始对象的引用,而不是副本。