1、基类的构造函数不被继承,派生类中需要声明自己的构造函数
2、声明构造函数时,只需要对类中新增成员进行初始化,对继承来的基类成员初始化(调用基类的构造函数完成)。
3、派生类的构造函数需要给基类的构造函数传递参数。
例子如下:
#include <iostream>
using namespace std;
class BaseObject{
public:
BaseObject(int bsobj){
cout<<"BaseObject(int bsobj)"<<endl;
}
~BaseObject(){
cout<<"~BaseObject()"<<endl;
}
};
class DerivedObject{
public:
DerivedObject(int dobj){
cout<<"DerivedObject(int dobj)"<<endl;
}
~DerivedObject(){
cout<<"~Object()"<<endl;
}
};
class Base
{
public:
int x_;
BaseObject baseObj;
Base(int bb):x_(bb),baseObj(20){
cout<<"Base(int bb)"<<""<<endl;
}
Base(const Base& other):baseObj(other.baseObj),x_(other.x_){//调用拷贝构造函数需要对x_成员进行初始化
}
~Base(){
cout<<"~Base()"<<endl;
}
protected:
private:
};
class Derived:public Base
{
public:
Derived(int a,int b,int c):y_(a),Base(b),obj(c){
cout<<"Derived(int b,int c)"<<endl;
}
Derived(const Derived& other):y_(other.y_),Base(other.y_),obj(other.obj){//调用拷贝构造函数
}
~Derived(){
cout<<"~Derived()"<<endl;
}
int y_;
DerivedObject obj;
protected:
private:
};
int main(){
Derived de1(100,200,300);
Derived de2(de1);
cout<<de1.x_<<"/:"<<de1.y_<<endl;
cout<<"de2.y_="<<de2.y_<<endl;
Base b1(400);
Base b2(b1);
cout<<b2.x_<<endl;
return 0;
}
注意:
(1)需要在构造函数的初始化列表中对成员进行初始化的情况有哪些呀?
1、const成员 例如 :const int n=10;
2、引用成员 int n2=100, int & rn=n2;
3、基类没有默认的构造函数的时候,基类的构造函数要在派生类的构造函数列表中进行调用。
4、类的对象成员没有默认构造函数的时候,只能够在类的构造函数初始化列表中调用该对象的构造函数进行初始化
(2)派生类的对象的构造次序(析构对象的次序正好相反)
首 先是调用基类对象成员的构造函数,然后是调用基类自身的构造数,其次是调用派生类对象成员的构造函数,最后是调用派生类对象自身的构造函数
//
静态的数据成员只有一份拷贝,并且基类和派生类是共享该拷贝的
#include <iostream>
using namespace std;
class Base
{
public:
static int b;
protected:
private:
};
int Base::b=10;
class Derived:public Base
{
public:
protected:
private:
};
int main(){
Derived de;
cout<<Derived::b<<endl;//推荐使用该方法访问变量
cout<<de.b<<endl;
cout<<Base::b<<endl;
return 0;
}