转换构造函数

Kol*_*nya 2 c++ constructor const type-conversion copy-constructor

试图编译代码:

class Foo
{
    public:
        Foo(Foo&){}
        Foo(int*){}
};

int main()
{
    int i = 2;
    Foo foo = &i;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

得到这个:

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&’
Run Code Online (Sandbox Code Playgroud)

我预计Foo foo = &i在线应该被称为Foo(int*)c-tor.

为什么编译器试图找到Foo::Foo(Foo)c-tor呢?

为什么不只使用现有的Foo(int*)c-tor?

当我添加const到第一个c-tor的参数时,为什么代码会编译?

当我完全删除第一个c-tor时,为什么代码会编译?

谢谢!

lee*_*mes 5

您的第一个构造函数是一个复制构造函数,不能用于从临时文件中复制.为此,您需要添加const,因此签名变为Foo(const Foo&).

下面的代码也编译(正确调用构造函数int*):

Foo foo(&i);
Run Code Online (Sandbox Code Playgroud)

您的代码Foo在赋值运算符的右侧创建一个(临时)对象,然后将此对象(使用(缺少的)复制构造函数)分配给foo.

编译器通常会自动为您生成一个复制构造函数,它接受一个const引用.但是由于您定义了一个构造函数Foo&,因此编译器不会为您生成这样的复制构造函数.因此删除第一个构造函数也会使代码编译.