2011-09-26 74 views
0

我有下面的C++代码:朋友操作人员的行为(常量VS非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函数中的前2个assign

有人可以向我解释为什么operator+返回constA

输出在Linux Debian 64bit和Windows 7 64位都是一样的。

+0

为什么狡猾的缩进? –

回答

8

根本没有返回const A.它返回一个临时的A,它只能绑定到const引用。

+0

在C++ 11中,临时对象也可以绑定到右值引用。 –