2011-09-26 3 views
0

나는 다음과 같은 C++ 코드를 가지고 :친구 연산자의 동작 (const가 아닌 대 const를)

#include <iostream> 

template <class T> 
void assign(T& t1, T& t2) { 
    std::cout << "First method" << std::endl; 
    t1 = t2; 
} 

template <class T> 
void assign(T& t1, const T& t2) { 
    std::cout << "Second method" << std::endl; 
    t1 = t2; 
} 

class A { 
    public: 
     A(int a) : _a(a) {}; 
    private: 
     int _a; 
     friend A operator+(const A& l, const A& r); 
}; 

A operator+(const A& l, const A& r) { 
    return A(l._a + r._a); 
} 

int main() { 
    A a = 1; 
    const A b = 2; 

    assign(a, a); 
    assign(a, b); 
    assign(a, a+b); 
} 

출력은 다음과 같습니다

First method 
Second method 
Second method 

출력은 내가 주석 경우에도 동일하게 유지를하여 처음에는 main 함수에 assign가 있습니다.

누군가가 내게 왜 operator+constA을 반환하는지 설명해 줄 수 있습니까?

출력은 Linux Debian 64bit와 Windows 7 64bit에서 동일합니다.

+0

어지러운 들여 쓰기가 필요한 이유는 무엇입니까? –

답변

8

const A가 반환되지 않습니다. const 참조에만 바인드 할 수있는 임시 A를 리턴합니다.

+0

C++ 11에서는 임시 변수가 rvalue 참조에 바인딩 될 수도 있습니다. –

관련 문제