C++程序的输出与预期不同的原因是什么?
What's the reason for different output than expected for C++ program?
我遇到了一个程序,它给出的输出与我预期的不同。可能是什么原因?
程序:
#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);
,以便返回对原始对象的引用而不是副本。
相关文章:
- 是否总是可以将使用递归编写的程序重写为不使用递归的程序C++,性能观点是什么?
- 使用动态链接加载程序 <dlfcn.h> 而不是直接函数调用的目的是什么?
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- 没有信号处理程序的POSIX定时器的目的是什么?
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 是什么原因导致我的SDL2程序中出现杂散像素
- 我的C++程序的工作目录是什么
- 是什么将程序集转换为实际可执行的材料
- 以下程序在 c++ 中的输出是什么?
- cpp中rand()方法的bankend程序是什么?
- 在Visual Studio中编写独立程序的最佳方法是什么?
- 应用程序仅在安装了 Visual Studio 的 PC 上启动.这种行为的原因可能是什么
- 在所有程序中,在Visual Studio中添加OpENCV的一般方法是什么?
- 对于我扩展此程序来计算最高10x10矩阵的倒数的最简单方法是什么
- 是什么导致程序在我继续执行另一个功能之前停止
- C++程序的输出与预期不同的原因是什么?
- 开发C++应用程序,目标服务器有不同的std lib版本,最佳实践是什么
- 以下程序背后的逻辑是什么
- 这个boost.python程序中的错误是什么?
- 程序崩溃的原因可能是什么,恕不另行通知