11中的隐式构造函数参数转换

11中的隐式构造函数参数转换

本文介绍了C ++ 11中的隐式构造函数参数转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下代码:

class A{
public:
  A(int x){}
};

class B{
public:
  B(A a){};
};


int main() {
  B b = 5;
  return 0;
}

在编译编译器时抱怨:

/home/test/main.cpp:80: candidate constructor not viable: no known conversion from 'int' to 'A' for 1st argument

我不想创建 B(int)构造函数-我希望编译器将此 int 隐式转换为 A 对象。

I don't want to create B(int) constructor - I would love the compiler to implicit convert this int to A object.

编辑:

直接初始化的过程如下:

Direct initialisation works like this:

B b(5);

是否可以使用分配运算符?

Is it possible to use the assigment operator instead?

推荐答案

只需明确一点:

B b = 5;

是复制初始化;没有分配。 (请参见)

is "copy initialisation" not assignment. (See http://www.gotw.ca/gotw/036.htm).

。在这种情况下,您要求编译器首先执行两个隐式的用户定义转换,即 int->。 A,A-> B ,然后将临时 B 对象传递给 B b 的副本构造函数。允许编译器取消临时对象,但是从语义上讲,您仍然要求语言在类型之间进行两次跳转。

In this case, you are asking the compiler to perform two implicit user-defined conversions first, i.e. int -> A, A -> B before a temporary B object is passed to the copy constructor for B b. The compiler is allowed to elide the temporary object but semantically you are still asking the language to make two jumps across types.

编程语言中的所有隐式行为本质上都是令人恐惧的。为了使用少量的语法糖,我们要求c ++做一些魔术使它能够正常工作。意外的类型转换会破坏大型复杂程序中的破坏。否则,每次您编写新函数或新类时,您都必须担心它可能影响的所有其他类型和函数,并且副作用会在您的代码中荡漾。
您真的要从 int ->进行隐式转换吗? 苹果-> -> 马力-> 飞机

All implicit behaviour in programming languages is inherently scary. For the sake of a little syntactic sugar, we are asking c++ to "do some magic to make it just work". Unexpected type conversions can wreck havoc in large complex programmes. Otherwise, every time you wrote a new function or a new class, you would have to worry about all the other types and functions it could affect, with the side -effects rippling across your code.Would you really want implicit conversions from int -> apple -> horse -> horse_power -> aeroplane?

因此,c ++只允许进行一次隐式的用户定义转换:

For that reason, c++ only allows a single implicit user-defined conversion:

12.3转换[class.conv]

4最多将一个用户定义的转换(构造函数或转换函数)隐式应用于单个值。

最好通过显式强制转换或直接初始化来实现。两者都使编译器和协作者可以清楚地知道您要执行的操作。无论是传统的还是新的统一初始化语法都可以使用:

You are better off either with an explicit cast or "direct initialisation" both of which make it clear to the compiler and collaborators exactly what you are trying to do. Either the traditional or the new uniform initialisation syntax works:

B b(5);
B b{5};
B b = {5};

这篇关于C ++ 11中的隐式构造函数参数转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:32