
现代C++中的委托构造函数(Delegating Constructors)是C++11引入的特性,它允许一个构造函数调用同一个类中的另一个构造函数,以避免代码重复。这种特性在初始化对象时提高了代码的复用性和清晰性。
1. 基本用法
在同一个类中,一个构造函数可以调用另一个构造函数,实现初始化代码的复用。
#include <iostream>
class MyClass {
public:
    MyClass() : MyClass(0) {  // 委托给另一个构造函数
        std::cout << "Default constructor" << std::endl;
    }
    MyClass(int value) : value(value) {
        std::cout << "Parameterized constructor with value " << value << std::endl;
    }
private:
    int value;
};
void basicDelegation() {
    MyClass obj1;    // 调用默认构造函数,它委托给参数化构造函数
    MyClass obj2(10); // 直接调用参数化构造函数
}
2. 避免代码重复
使用委托构造函数可以避免在多个构造函数中重复相同的初始化代码。
#include <iostream>
#include <string>
class Person {
public:
    Person() : Person("Unnamed", 0) {
        std::cout << "Default constructor called" << std::endl;
    }
    Person(const std::string& name, int age) : name(name), age(age) {
        std::cout << "Parameterized constructor called" << std::endl;
    }
private:
    std::string name;
    int age;
};
void avoidDuplication() {
    Person person1;                  // 调用默认构造函数,它委托给参数化构造函数
    Person person2("John Doe", 30);  // 直接调用参数化构造函数
}
3. 构造函数的选择逻辑
在委托构造函数中,可以根据条件逻辑决定委托哪个构造函数。
#include <iostream>
#include <string>
class Widget {
public:
    Widget() : Widget("Default", false) {
        std::cout << "Default widget created" << std::endl;
    }
    Widget(const std::string& name, bool isShown) : name(name), isShown(isShown) {
        std::cout << "Widget " << name << " created, shown: " << isShown << std::endl;
    }
private:
    std::string name;
    bool isShown;
};
void constructorLogic() {
    Widget widget1;                 // 默认构造函数,委托给参数化构造函数
    Widget widget2("Custom", true); // 直接调用参数化构造函数
}
4. 注意事项
- 构造函数委托不能形成环。
- 委托构造函数在进入目标构造函数前,不会初始化任何成员。
通过委托构造函数,开发者可以减少初始化代码的冗余,使得构造函数的维护更加方便,同时保持初始化逻辑的清晰。

![[闲聊统计]之参数估计是什么?(下)](https://img-blog.csdnimg.cn/img_convert/736c062c752df2a9720444c576c088a0.png)

















