C++拷贝初始化+隐式构造函数call = fail

fin*_*ncs 1 c++ constructor implicit-conversion copy-initialization c++11

这段代码:

class foo
{
    int x;
public:
    foo(int x) : x(x) { }
    int get() const { return x; }
    //...
};

class bar
{
    int x;
public:
    bar(const foo& x) : x(x.get()) { }
    int get() const { return x; }
    bar& operator =(const foo& rhs) { x = rhs.get(); return *this; }
    //...
};

void func()
{
    foo f = 3;
    bar b = 3;
    b = 7;
    //...
}
Run Code Online (Sandbox Code Playgroud)

在线上出错bar b = 3(g ++ 4.7.1 with -fstd=gnu++11):

error: conversion from 'int' to non-scalar type 'bar' requested
Run Code Online (Sandbox Code Playgroud)

但是,我提供了一个带有a的bar构造函数foo,并且可以隐式转换为int,foo如前面的行所示.那么,出了什么问题?

顺便说一句,由于几个原因,强制转换为foo使用是不可取的,foo(3)因为这会使我的实际代码难以使用和阅读.

Naw*_*waz 5

我提供了一个带有foo的bar构造函数,并且int可以隐式转换为foo,如前面的行所示.那么,出了什么问题?

C++中不允许链式转换,这意味着不会发生(链式)转换:

int -> foo -> bar  //not allowed (chained conversion)
Run Code Online (Sandbox Code Playgroud)

即使给出以下内容:

int -> foo  //given
foo -> bar  //given
Run Code Online (Sandbox Code Playgroud)

因此,如果您想要int -> bar工作,那么添加另一个构造函数int到课堂bar.