2013-11-28 66 views
2

当返回对调用函数的对象的引用时,可以使用返回的引用将函数调用链接到单个对象上。为什么第二个程序的输出与第一个程序不同?

在这里,我正在应用相同的概念。但是如果我以不同的方式初始化对象,我会得到不同的输出。

第一个例子:

#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。它与众不同的原因是什么?

+4

您标记了此C#,但您的代码似乎是C++,这是什么? –

+0

对不起我的错误 –

回答

5

区别在于程序的第二个版本按值返回。这意味着第二个呼叫(即setY)在obj1副本上执行,而不是在obj1本身上执行。这就是为什么只有X最终被设置,而不是Y

另一方面,在你的第一个程序中,设置者返回他们的结果作为参考。这意味着没有拷贝,所以setY在与setX相同的对象上被调用,而不是其副本。

+0

然后为什么它的设置** x **只为什么不** ** y也 –

+1

@vivekjain因为初始调用(即'setX')是在对象本身完成的,所以在setter创建之前复制(隐式地,通过值返回)。 – dasblinkenlight

相关问题