更新:建议的重复问题只解决了这个问题的一部分。理解正在发生的事情(首先创建临时引用)的关键在那里没有得到解释。
这是我第一次遇到隐式转换,所以我写了这个:
class A {};
class B {
public:
B(A& other) {}
// Copy constructor
B(const B& other) {}
};
int main() {
A foo;
B bar = foo;
}
这段代码编译时没有问题,但如果我去掉const
关键字,我的编译器(gcc 版本 4.8.4)会在赋值处报错,错误信息让我无法理解:
test.cc: In function ‘int main()’:
test.cc:12:13: error: no matching function for call to ‘B::B(B)’
B bar = foo;
^
test.cc:12:13: note: candidates are:
test.cc:7:5: note: B::B(B&)
B(B& other) {}
^
test.cc:7:5: note: no known conversion for argument 1 from ‘B’ to ‘B&’
test.cc:5:5: note: B::B(A&)
B(A& other) {}
^
test.cc:5:5: note: no known conversion for argument 1 from ‘B’ to ‘A&’
这是有效的C++代码吗?为什么当我一开始尝试将 A
赋值时,它会显示 no matching function for call to ‘B::B(B)’
?
const
,则B bar(foo);
可以正常工作而不会出现任何问题。 - jpo38const
也能正常工作。 - dbush