尝试编译代码:
class Foo
{
public:
Foo(Foo&){}
Foo(int*){}
};
int main()
{
int i = 2;
Foo foo = &i;
return 0;
}
得到这个:
prog.cpp: In function ‘int main()’:
prog.cpp:11:16: error: no matching function for call to ‘Foo::Foo(Foo)’
prog.cpp:11:16: note: candidates are:
prog.cpp:5:9: note: Foo::Foo(int*)
prog.cpp:5:9: note: no known conversion for argument 1 from ‘Foo’ to ‘int*’
prog.cpp:4:9: note: Foo::Foo(Foo&)
prog.cpp:4:9: note: no known conversion for argument 1 from ‘Foo’ to ‘Foo&’
我原以为Foo foo = &i
线上应该叫Foo(int*)
c-tor。
为什么编译器会尝试查找Foo::Foo(Foo)
c-tor?
为什么它不只使用存在的Foo(int*)
c-tor?
const
为什么当我添加到第一个 c-tor 的参数时代码会编译?
为什么当我完全删除第一个 c-tor 时代码会编译?
谢谢!