另一个例子
让我们来看看另一个对课我们曾与一看:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#include <string>
class
Person
{
public
:
std::string m_strName;
int
m_nAge;
bool
m_bIsMale;
std::string GetName() {
return
m_strName; }
int
GetAge() {
return
m_nAge; }
bool
IsMale() {
return
m_bIsMale; }
Person(std::string strName =
""
,
int
nAge = 0,
bool
bIsMale =
false
)
: m_strName(strName), m_nAge(nAge), m_bIsMale(bIsMale)
{
}
};
// BaseballPlayer publicly inheriting Person
class
BaseballPlayer :
public
Person
{
public
:
double
m_dBattingAverage;
int
m_nHomeRuns;
BaseballPlayer(
double
dBattingAverage = 0.0,
int
nHomeRuns = 0)
: m_dBattingAverage(dBattingAverage), m_nHomeRuns(nHomeRuns)
{
}
};
|
正如我们以前写的,baseballplayer只初始化它的成员并没有指定要使用的一个构造函数。这意味着每一个baseballplayer我们创建将要使用的默认构造函数初始化的人,将名字空白和年龄0。因为它让我们baseballplayer名字和年龄当我们创造它们,我们应该修改这个构造函数将这些参数。
这是我们的新baseballplayer类的构造函数调用人构造函数初始化成员变量的继承人。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// BaseballPlayer publicly inheriting Person
class
BaseballPlayer :
public
Person
{
public
:
double
m_dBattingAverage;
int
m_nHomeRuns;
BaseballPlayer(std::string strName =
""
,
int
nAge = 0,
bool
bIsMale =
false
,
double
dBattingAverage = 0.0,
int
nHomeRuns = 0)
: Person(strName, nAge, bIsMale),
// call Person(std::string, int, bool) to initialize these fields
m_dBattingAverage(dBattingAverage), m_nHomeRuns(nHomeRuns)
{
}
|