Posted on 2011-07-17 20:47
susu 阅读(617)
评论(0) 编辑 收藏 引用
1![](/Images/OutliningIndicators/None.gif)
2
#include<iostream>
3
#include <cmath>
4
using namespace std;
5![](/Images/OutliningIndicators/None.gif)
6
class B1 //基类B1,构造函数有参数
7![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{public:
8![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
B1(int i)
{cout<<"constructing B1 "<<i<<endl;}
9
};
10
class B2 //基类B2,构造函数有参数
11![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{public:
12![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
B2(int j)
{cout<<"constructing B2 "<<j<<endl;}
13
};
14
class B3 //基类B3,构造函数无参数
15![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{public:
16
//B3(){cout<<"constructing B3 *"<<endl;}
17![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
void B5()
{cout<<"constructing B3 *"<<endl;}
18
};
19![](/Images/OutliningIndicators/None.gif)
20
class C: public B2, public B1, public B3
21![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
22
public: //派生类的公有成员
23
C(int a, int b, int c, int d):
24![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
B2(b),B1(a),memberB1(c),memberB2(d)
{}
25![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//*
26
说明:此处B3 类中没有参数,所以在此处不用对B3进行构造函数赋值操作,
27
这里出现的“:”后的定义必须在类的继承后面“:”中已经定义了
28
即B2和B1均继承了,不过B3虽然继承了,但是构造函数中没有值,所以就不用在这里多加说明
29
另外的memberB1(c),memberB2(d),但这种是对本类中的成员进行初始化操作。memberB1(c)
30
不过这里感觉会有点怪:
31
不是类似的 x = a;类的形式赋值。
32
*/
33
private: //派生类的私有对象成员
34
B1 memberB1;
35
B2 memberB2;
36
//B3 memberB3;
37
B3 t;
38
};
39
void main()
40![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{ C obj(1,2,3,4); }
41![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//*
42
记住以下规定:
43
当基类中声明有默认形式的构造函数或未声明构造函数时,派生类构造函数可以不向基类构造函数传递参数。
44
若基类中未声明构造函数,派生类中也可以不声明,全采用缺省形式构造函数。
45
当基类声明有带形参的构造函数时,派生类也应声明带形参的构造函数,并将参数传递给基类构造函数。
46![](/Images/OutliningIndicators/InBlock.gif)
47![](/Images/OutliningIndicators/InBlock.gif)
48
1. 调用基类构造函数,调用顺序按照它们被继承时声明的顺序(从左向右)。
49
2. 调用成员对象的构造函数,调用顺序按照它们在类中声明的顺序。
50
3. 派生类的构造函数体中的内容。
51![](/Images/OutliningIndicators/InBlock.gif)
52
派生类名::派生类名(基类1形参,基类2形参,
基类n形参,本类形参):基类名1(参数), 基类名2(参数),
基类名n(参数),对象数据成员的初始化
53
{
54
本类成员初始化赋值语句;
55
};
56![](/Images/OutliningIndicators/InBlock.gif)
57
*/