有了委派構造函數,就不用每個構造版本都做同樣的初始化工作,隻需要不斷形參少的委派就行了
以下是《深入了解c++11》中的截圖

以下是自己的實作
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
/*
委派構造函數的使用,類似與構造基類
*/
class Info
{
public:
Info() { init(); }
//Info(int _age) : Info(), mName("qwe") //無法編譯通過,不能同時 委派 和 初始化成員,如果需要初始化成員,必須放在構造函數體中
Info(int _age) : Info()
{
mAge = _age;
printf("--- one param mAge:%d\n", mAge);
}
Info(int _age, std::string _name) : Info(_age)
{
mName = _name;
printf("--- two param mName:%s\n", mName.c_str());
}
private:
void init(){ mHeight = 1.23f; printf("--- init mheight:%f\n", mHeight); }
int mAge;
std::string mName;
float mHeight;
};
void testDelegatingConstructor()
{
Info info(77, "yang");
/*
--- init mheight:1.230000
--- one param mAge:77
--- two param mName:yang
請按任意鍵繼續. . .
*/
}