我寫了下面的代碼:無法理解編譯器的行爲(創建對象)
#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