▌继承中不能继承的三个部分:
①构造函数:子类的构造函数应该先调用基类的构造函数来初始化其从基类继承过来的部分,然后在函数体(花括号中)初始化自己的附加部分。如果不用成员初始化列表则不能初始化成员。当基类的构造函数带有参数的时候,子类构造函数中要提供这些参数,在成员初始化列表中也要带上参数(但是不用写返回类型)。子类中的拷贝构造函数在定义的时候要先调用基类的拷贝构造函数。
②析构函数:调用子类的析构函数的时候,子类会自动调用基类的析构函数来析构从基类继承来的那部分空间。
③赋值运算符重载:子类的赋值函数首先要在函数体里({}里)调用基类的赋值函数,来把基类部分进行赋值,再次进行附加部分的赋值。
例:
class Base
{
Base(int a);
};
class Derived:public Base;
Derived::Derived(int a):Base(a){
//写代码来初始化附加部分;
}
Derived::~Derived(){
//写代码来析构附加部分;
}
例:
const Derived&Derived::operator=(const Derived& d)
{
if (this !=&d)
{
delete [] label;
Base::operator=(d); //调用基类中的赋值函数来赋值从基类继承来的部分;
f=d.f;
if (!d.label) {label=NULL;}
else
{
label=new char [strlen(d.label)+1];
strcpy(label, d.label);
}
cout << "derived assignmentoperator\n";
}
return *this;
}