简体   繁体   English

C ++复制初始化+隐式构造函数调用=失败

[英]C++ copy initialization + implicit constructor call = fail

This code: 这段代码:

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;
    //...
}

errors out on the bar b = 3 line (g++ 4.7.1 with -fstd=gnu++11 ): bar b = 3行上出现错误(g ++ 4.7.1和-fstd=gnu++11 ):

error: conversion from 'int' to non-scalar type 'bar' requested

However, I'm providing a bar constructor that takes a foo , and ints can be implicitly converted to foo as shown by the line preceding it. 但是,我提供了一个使用foobar构造函数,并且可以将ints隐式转换为foo如其前一行所示。 So, what is going wrong? 那么,出了什么问题?

By the way, for several reasons it is undesirable to force conversion to foo using foo(3) because that would make my actual code ugly to use and read. 顺便说一下,由于多种原因,不希望使用foo(3)强制转换为foo因为那样会使我的实际代码难以使用和读取。

I'm providing a bar constructor that takes a foo, and ints can be implicitly converted to foo as shown by the line preceding it. 我提供了一个带有foo的bar构造函数,并且可以将ints隐式转换为foo,如其前一行所示。 So, what is going wrong? 那么,出了什么问题?

Chained-conversion is not allowed in C++, which means the (chained) conversion cannot occur: 在C ++中不允许链式转换,这意味着(链式)转换不会发生:

int -> foo -> bar  //not allowed (chained conversion)

even though the followings are given: 即使给出以下内容:

int -> foo  //given
foo -> bar  //given

So if you want int -> bar to work, then add another constructor taking int to class bar . 因此,如果您要让int -> bar正常工作,请在bar类中添加另一个使用int构造函数。

§ 13.3.3.1.2/1 about implicit user-defined conversion sequences mandates: 第13.3.3.1.2 / 1条关于隐式用户定义的转换序列的规定:

A user-defined conversion sequence consists of an initial standard conversion sequence followed by a user defined conversion (12.3) followed by a second standard conversion sequence . 用户定义的转换序列由初始的标准转换序列,后面的用户定义的转换(12.3)和第二个标准转换序列组成 If the user-defined conversion is specified by a constructor (12.3.1), the initial standard conversion sequence converts the source type to the type required by the argument of the constructor. 如果用户定义的转换是由构造函数(12.3.1)指定的,则初始标准转换序列会将源类型转换为构造函数的参数所需的类型。 If the user-defined conversion is specified by a conversion function (12.3.2), the initial standard conversion sequence converts the source type to the implicit object parameter of the conversion function. 如果用户定义的转换是由转换函数(12.3.2)指定的,则初始标准转换序列会将源类型转换为转换函数的隐式对象参数。

This means it is not possible to chain more than one user-defined conversion. 这意味着不可能链接多个用户定义的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM