当返回对调用函数的对象的引用时,可以使用返回的引用将函数调用链接到单个对象上。为什么第二个程序的输出与第一个程序不同?
在这里,我正在应用相同的概念。但是如果我以不同的方式初始化对象,我会得到不同的输出。
第一个例子:
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1(5, 5);
// Chained function calls. All calls modify the same object
// as the same object is returned by reference
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
输出是10和20,这是正确的。
然而,输出不用于第二示例纠正:
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
Test setX(int a) { x = a; return *this; }
Test setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1;
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
输出是10和0。
为什么呢?我认为两者都是一样的,第二个程序的输出也应该是10和20。它与众不同的原因是什么?
您标记了此C#,但您的代码似乎是C++,这是什么? –
对不起我的错误 –