c++ - C++中的构造函数链接

标签 c++ constructor specifications constructor-chaining

我对构造函数链接的理解是,当一个类中有多个构造函数(重载构造函数)时,如果其中一个试图调用另一个构造函数,那么 这个过程称为 CONSTRUCTOR CHAINING ,在 C++ 中不受支持。 最近在看网上资料的时候偶然发现了这一段……是这样的……

You may find yourself in the situation where you want to write a member function to re-initialize a class back to default values. Because you probably already have a constructor that does this, you may be tempted to try to call the constructor from your member function. As mentioned, chaining constructor calls are illegal in C++. You could copy the code from the constructor in your function, which would work, but lead to duplicate code. The best solution in this case is to move the code from the constructor to your new function, and have the constructor call your function to do the work of initializing the data.

调用构造函数的成员函数是否也属于构造函数链? 请用 C++ 阐明这个主题。

最佳答案

C++11 允许构造函数链接(部分)。此功能称为“delegating constructors”。因此,在 C++11 中,您可以执行以下操作

class Foo
{
public:
    Foo(int a) : Foo() { _a = a; }
    Foo(char* b) : Foo() { _b = b; }
    Foo() { _c = 1.5; }
private:
    int _a = 0;
    char* _b = nullptr;
    double _c;
};

但是,有一个严格的限制,即不允许调用另一个构造函数的构造函数来初始化任何其他成员。因此,您不能使用委托(delegate)构造函数执行以下操作:

class Foo
{
public:
    Foo(int a) : Foo(), _a(a) { }
    Foo(char* b) : Foo(), _b(b) { }
    Foo() { _c = 1.5; }
private:
    int _a = 0;
    char* _b = nullptr;
    double _c;
};

MSVC++2013 给出后一个代码示例的编译错误“C3511:对委托(delegate)构造函数的调用应是唯一的成员初始化程序”。

关于c++ - C++中的构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7349183/

相关文章:

c++ - std::array 和字节读取

c++ - 在 OpenGL 中为 freetype 设置模型矩阵时类似笔的行为

c# - 在 C# 中使构造函数仅接受具有 [Serializable] 属性的对象

documentation - 共享规范的软件/平台

c++ - 为什么在向上转换后调用派生类的虚方法?

c++ - 使用特定于 2012 年 11 月 CTP 的 C++11 功能时,有没有办法抑制 Intellisense 错误?

c# - 有没有办法在 C# 中从构造函数中初始化字段?

c++ - 什么是 C++ 中的转换构造函数?它是干什么用的?

java - 不明白如何使用 GridLayout.spec()

java - Spring Data Jpa - 类型规范<T>已弃用