我听说 C++ 有一个叫做“转换构造函数”或“转换构造函数”的东西。这些是什么,它们是做什么用的?我看到它提到了这段代码:
class MyClass
{
public:
int a, b;
MyClass( int i ) {}
}
int main()
{
MyClass M = 1 ;
}
最佳答案
转换构造函数的定义在 C++03 和 C++11 之间是不同的。在这两种情况下,它都必须是非explicit
构造函数(否则它不会参与隐式转换),但对于 C++03,它也必须可以使用单个参数调用。那就是:
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 不是转换构造函数,因为它是 explicit
。
C++03:§12.3.1
A constructor declared without the function-specifier
explicit
that can be called with a single parameter specifies a conversion from the type of its first parameter to the type of its class. Such a constructor is called a converting constructor.C++11:§12.3.1
A constructor declared without the function-specifier
explicit
specifies a conversion from the types of its parameters to the type of its class. Such a constructor is called a converting constructor.
为什么在 C++11 中将具有多个参数的构造函数视为转换构造函数?这是因为新标准为我们提供了一些方便的语法,用于使用 braced-init-lists 传递参数和返回值。考虑以下示例:
foo bar(foo f)
{
return {1.0f, 5};
}
将返回值指定为 braced-init-list 的能力被视为一种转换。这使用了 foo
的转换构造函数,它接受一个 float
和一个 int
。另外,我们可以通过bar({2.5f, 10})
来调用这个函数。这也是一种转换。由于它们是转换,因此它们使用的构造函数是转换构造函数。
因此,重要的是要注意,使 foo
的构造函数采用 float
和 int
具有 显式
函数说明符将阻止上述代码编译。上面的新语法只有在有一个转换构造函数可用时才能使用。
C++11:§6.6.3:
A
return
statement with a braced-init-list initializes the object or reference to be returned from the function by copy-list-initialization (8.5.4) from the specified initializer list.§8.5:
The initialization that occurs [...] in argument passing [...] is called copy-initialization.
§12.3.1:
An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used.
关于c++ - 什么是 C++ 中的转换构造函数?它是干什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15077466/