class MyClass {
public:
...
MyClass & operator=(const MyClass &rhs); // return MyClass&
...
}
왜 안C++ - 연산자가 * this 대신 * this에 대한 참조를 반환하는 이유는 무엇입니까?
class MyClass {
public:
...
MyClass operator=(const MyClass &rhs); // return MyClass
...
}
이 경우 참조로 반환하는 것이 더 효율적이라는 이유인가?
감사합니다
// * 업데이트 *
나는 다음과 같이 나는 주된 이유를 찾은 것 같아 : 연산자의 반환 형식은 = MyClass에보다는 MyClass에있다
int i1, it2, i3;
(i1 = i2) = i3; // i3 will be assigned to i1
경우 &이면 다음 문은 내부 데이터 형식과 동일하게 수행되지 않습니다.
MyClass mc1, mc2, mc3;
(mc1 = mc2) = mc3;
내장 유형에 사용되는 규칙을 따르면 우수 사례로 간주됩니다.
// *** update ***
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i1, i2, i3;
i1 = 0;
i2 = 2;
i3 = 3;
(i1 = i2) = i3;
cout << "i1: " << i1 << endl;
cout << "i2: " << i2 << endl;
cout << "i3: " << i3 << endl;
return 0;
}
// output from VS2010
/*
i1: 3
i2: 2
i3: 3
*/
이 비슷한 질문을 참조하십시오 : (http://stackoverflow.com/q/2447696/478288) – chrisaycock
아니,'i3'가 할당되지 않습니다 [C++에서 과부하 할당 연산자]를 'i1'. 사실이 동작은'(i1 = i2) = i3' 할당에서 정의되지 않습니다. – AnT
@AndreyT : 내 update2를 참조하십시오. – q0987