问题描述
我听说C ++有一些名为转换构造函数或转换构造函数的东西。这些是什么,它们是什么?我看到它提到关于这个代码:
I have heard that C++ has something called "conversion constructors" or "converting constructors". What are these, and what are they for? I saw it mentioned with regards to this code:
class MyClass { public: int a, b; MyClass( int i ) {} } int main() { MyClass M = 1 ; }
推荐答案
转换构造函数在C ++ 03和C ++ 11之间是不同的。在这两种情况下,它必须是一个非 - 显式的构造函数(否则它不会涉及隐式转换),但对于C ++ 03它也必须可调用单参数。即:
The definition for a converting constructor is different between C++03 and C++11. In both cases it must be a non-explicit constructor (otherwise it wouldn't be involved in implicit conversions), but for C++03 it must also be callable with a single argument. That is:
struct foo { foo(int x); // 1 foo(char* s, int x = 0); // 2 foo(float f, int x); // 3 explicit foo(char x); // 4 };
构造函数1和2都是C ++ 03和C ++ 11中的转换构造函数。构造函数3必须带有两个参数,它只是C ++ 11中的转换构造函数。最后一个构造函数4不是转换构造函数,因为它显式。
Constructors 1 and 2 are both converting constructors in C++03 and C++11. Constructor 3, which must take two arguments, is only a converting constructor in C++11. The last, constructor 4, is not a converting constructor because it is explicit.
-
C ++ 03 :§12.3.1
C ++ 11 :§12.3。 1
C++11: §12.3.1
一个参数被认为是转换C ++ 11中的构造函数?这是因为新标准为我们提供了一些方便的语法,用于传递参数和使用 braced-init-lists 返回值。考虑下面的例子:
Why are constructors with more than a single parameter considered to be converting constructors in C++11? That is because the new standard provides us with some handy syntax for passing arguments and returning values using braced-init-lists. Consider the following example:
foo bar(foo f) { return {1.0f, 5}; }
能够将返回值指定为 braced-init-列表被视为转化。这使用 foo 的转换构造函数,它使用 float 和 int 。此外,我们可以通过 bar({2.5f,10})调用此函数。这也是一个转换。由于它们是转换,因此它们使用的构造函数是转换构造函数。
The ability to specify the return value as a braced-init-list is considered to be a conversion. This uses the converting constructor for foo that takes a float and an int. In addition, we can call this function by doing bar({2.5f, 10}). This is also a conversion. Since they are conversions, it makes sense for the constructors they use to be converting constructors.
因此,重要的是要注意, foo 的构造函数,它接受 float 和 int 有 explicit 函数说明符将停止上述代码的编译。
It is important to note, therefore, that making the constructor of foo which takes a float and an int have the explicit function specifier would stop the above code from compiling. The above new syntax can only be used if there is a converting constructor available to do the job.
-
C + +11 :§6.6.3:
§8.5:
§12.3.1:
这篇关于什么是C ++中的转换构造函数?它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!