1. 回忆继承
我们知道,在C++的继承体系中,子类继承父类时,会将父类除了构造函数和析构函数以外的所有数据都继承下来。
子类中如果有与父类名字相同的方法,子类将隐藏父类方法,优先使用子类方法。
划重点:子类继承不会继承父类的构造和析构函数,同名方法会被子类隐藏。
2. 继承构造函数语法:using Base::Base
正因为子类没法继承父类的构造函数,所以我们在C++11之前,需要在子类的初始化列表中显式的调用基类的构造函数或者默认构造函数。
基类,有三个构造函数的重载版本:
class Base{
public:
Base(int ma) :ma_(ma) { cout << "Base(int)" << endl; }
Base(int ma, double mb) :ma_(ma), mb_(mb) { cout << "Base(int,double)" << endl; }
Base(int ma, double mb, std::string str) :ma_(ma), mb_(mb), mstr_(str) { cout << "Base(int,double,string)" << endl; }
void fun(float p) { cout << "Base::fun" << endl; }
void fun(float p, int a) { cout << "Base::fun" << endl; }
int ma_;
double mb_;
std::string mstr_;
};
在C++11前如果调用对应的构造函数版本时,是这样使用的:
class Deriver1 :public Base {
public:
Deriver1(int i) :Base(i) { cout << "Deriver1(int)" << endl; }
Deriver1(int i, double j) :Base(i, j) { cout << "Deriver1(int,double)" << endl; }
Deriver1(int i, double j, string k) :Base(i, j, k) { cout << "Deriver1(int,double,string)" << endl; }
};
C++11开始可以使用using显式声明需要继承基类的构造函数:
class Deriver2 :public Base {
public:
using Base::Base;
};
int main() {
Deriver2 d1(10);
Deriver2 d2(10, 0.0);
Deriver2 d3(10, 0.0, "string");
return 0;
}
3. 我们还可以在子类中使用基类方法而不需要加作用域访问:using Base::fun
class Base{
public:
Base(int ma) :ma_(ma) { cout << "Base(int)" << endl; }
Base(int ma, double mb) :ma_(ma), mb_(mb) { cout << "Base(int,double)" << endl; }
Base(int ma, double mb, std::string str) :ma_(ma), mb_(mb), mstr_(str) { cout << "Base(int,double,string)" << endl; }
void fun(string p) { cout << "Base::fun" << endl; }
void fun(float p, int a) { cout << "Base::fun" << endl; }
int ma_;
double mb_;
std::string mstr_;
};
class Deriver :public Base {
public:
using Base::Base;
using Base::fun;
void fun(int p) { cout << "Deriver3::fun" << endl; }
};
int main() {
Deriver d(10, 0.0, "string");
//Base::fun
d.fun("call Base::fun");
d.fun(1.1,2);
//Deriver::fun
d.fun(1);
return 0;
}