我写了下面的代码:无法理解编译器的行为(创建对象)
#include <iostream>
class A
{
public:
A(){ std::cout << "created" << std::endl; }
A(A& other) { std::cout << "copied" << std::endl; }
A& get(){ std::cout <<"got" << std::endl; return *this; }
~A(){ std::cout << "destroyed" << std::endl; }
};
现在,线
A a = A().get();
和
A a;
a = A();
编译和正常工作,但
A a = A();
个
声称:
no matching function for call to ‘A::A(A)’
note: candidates are: A::A(A&)
note: A::A()
使事情明确,
A a = (A&)A();
声称:
error: invalid cast of an rvalue expression of type ‘A’ to type ‘A&’
我完全不理解这种行为。
P.S.我知道,如果我在复制c_tor中创建const
引用,则一切都会好的。
这个解释听起来对我来说最合乎逻辑 – Lol4t0