委托构造函数
先来看下,我们类的构造函数不使用委托构造的情况
class AA{
public:
int first;
int second;
int third;
AA() {}
AA(int first) {
this->first = first;
}
AA(int first, int second) {
this->first = first;
this->second = second;
}
AA(int first, int second, int third) {
this->first = first;
this->second = second;
this->third = third;
}
};
可以看到上述的所有构造函数,存在重复代码
使用委托构造函数
class AA{
public:
int first;
int second;
int third;
AA() {}
AA(int first) {
this->first = first;
}
AA(int first, int second) :AA(first){
this->second = second;
}
AA(int first, int second, int third): AA(first, second) {
this->third = third;
}
};
继承构造函数
class AA{
public:
int first;
double second;
string third;
AA(int first, double second, string third) {
this->first= first;
this->second = second;
this->third = third;
}
};
class Child :public AA {
public:
using AA::AA; // 使用using AA::AA;后,子类就可以直接使用父类的构造函数了
};
int main() {
Child child(22, 3.14, "hello world");
return 0;
}
``
网友评论