您的位置:首页 > 其它

派生类中构造函数与虚构函数的研究

2016-07-20 23:07 176 查看

1.继承过程中的构造函数

A:继承与派生过程中,基类的构造函数不能被继承,派生类中需要声明自己的构造函数。
B:声明构造函数时,只需要对本类中新增成员进行初始化。至于基类继承过来的成员,应该调用基类的构造函数来完成
C:需要强调的是,派生类的构造函数需要给基类的构造函数传递参数

1.1 单一继承时的构造函数

基本公式:
派生类名(基类所需要的形参,派生类成员所需的形参):基类名(参数表)
{
本类成员初始化赋值语句;
}
#include<iostream>
using namespace std;

class B{
public:
B();
B(int i);
~B();
void Print() const;
private:
int b;
};
B::B()
{	b=0;
cout<<"B's default constructor called."<<endl;
}
B::B(int i)
{	b=i;
cout<<"B's constructor called." <<endl;
}
B::~B()
{	cout<<"B's destructor called."<<endl;  }
void B::Print() const
{	cout<<b<<endl;  }

class C:public B
{
public:
C();
C(int i,int j);
~C();
void Print() const;
private:
int c;
};
C::C() //自动调用基类B的默认构造函数
{	c=0;
cout<<"C's default constructor called."<<endl;
}
C::C(int i,int j):B(i) //显式调用基类B的含有参数的构造函数
{	c=j;
cout<<"C's constructor called."<<endl;
}
C::~C()
{	cout<<"C's destructor called."<<endl; }
void C::Print() const
{	B::Print();	cout<<c<<endl;  }
void main()
{
C cc;
C obj(5,6);
obj.Print();
}

运行结果:



1.2 多继承时的构造函数

基本公式:
派生类名(基类1形参,基类2形参,...,基类n形参,本类形参):基类名1(参数),基类名2(参数),...,基类名n(参数)
{
     本类新增参数进行赋值;
}
#include <iostream>
using namespace std;

class B1{
public:
B1(int i) {cout<<"constructing B1 "<<i<<endl;}
};
class B2{
public:
B2(int j) {cout<<"constructing B2 "<<j<<endl;}
};
class B3{
public:
B3() {cout<<"constructing B3 *"<<endl;}
};
///////////////////////////////////////////////////
class C: public B1, public B2, public B3{
public:
C(int a,int b, int c,int d):
memobj1(c),B1(a),B2(b),memobj2(d) {}
private:
B2 memobj2;
B1 memobj1;
B3 memobj3;
};
void main()
{
C obj(1,2,3,4);
}
运行结果:



1.3 派生类中构造函数的调用次序

A:调用基类构造函数,调用顺序按照他们被继承时声明的顺序
B:调用成员对象的构造函数,调用顺序按照他们在类中声明的顺序
C:执行派生类构造函数中的内容

1.4 派生类中的构造函数

A:若建立派生类对象时调用了缺省的拷贝构造函数,则编译器将自动调用基类缺省的拷贝构造函数
B:   若编写派生类的拷贝构造函数,则需要为基类相应的拷贝构造函数传递参数,例如C(C &c1):B(c1) {}

2.继承时的析构函数

A:基类的析构函数也不能被继承,派生类需要自行声明
B:声明的方法与一般(无继承关系)类的析构函数相同
C:不需要显式地调用基类的析构函数,系统会自动的隐式调用
D:析构函数的调用次序与构造函数相反
#include <iostream>
using namespace std;

class B1{
public:
B1(int i) {cout<<"constructing B1 "<<i<<endl;}
~B1() {cout<<"destructing B1 "<<endl;}
};
class B2{
public:
B2(int j) {cout<<"constructing B2 "<<j<<endl;}
~B2() {cout<<"destructing B2 "<<endl;}
};
class B3{
public:
B3() {cout<<"constructing B3 *"<<endl;}
~B3() {cout<<"destructing B3 "<<endl;}
};
///////////////////////////////////////////////////
class C: public B1, public B2, public B3{
public:
C(int a,int b, int c,int d):
memobj1(c),B1(a),B2(b),memobj2(d) {cout<<"constructing C "<<endl;}
private:
B2 memobj2;
B1 memobj1;
B3 memobj3;
};
void main()
{
C obj(1,2,3,4);
}
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: