3-3 保护继承和私有继承
例子:
上图:线段类Line只能访问到m_coorA和m_coorB的公有数据成员和公有成员函数;
线段和坐标的关系是Has a的关系(包含关系),私有继承也是一种包含关系,当我们定义了一个子类的对象的时候,子类对象就包含了一个父类对象,因为它只能访问父类中公有的数据成员和成员函数(被保护的呢?:protected对于子女、朋友来说,就是public的,可以自由使用,没有任何限制,而对于其他的外部class,protected就变成private;所以此处的公有的数据成员包括public和protected),所以从本质上来说私有继承也是一种Has a的关系;
3-4 保护继承和私有继承代码演示
Person.h
#include <string>
using namespace std;//class也在std里面
class Person
{
public:
Person();
void play();
protected:
string m_strName;
};
Person.cpp
#include "Person.h"
#include <iostream>
using namespace std;
Person::Person()
{
m_strName = "Merry";
}
void Person::play()
{
cout<<m_strName<<endl;
cout<<"Person - play()"<<endl;
}
Soldier.h
#include "Person.h"
class Soldier:protected Person
{
public:
Soldier();
void work();
protected:
int m_iAge;
};
Soldier.cpp
#include <iostream>
#include "Soldier.h"
using namespace std;
Soldier::Soldier()
{
}
void Soldier::work()
{
m_strName = "Jim";
m_iAge = 20;
cout<<m_strName<<endl;
cout<<m_iAge<<endl;
cout<<"Soldier - work"<<endl;
}
Infantry.h
#include "Soldier.h"
class Infantry:public Soldier
{
public:
void attack();
};
Infantry.cpp
#include <iostream>
#include "Infantry.h"
using namespace std;
void Infantry::attack()
{
m_strName = "Jerry";
cout<<m_strName<<endl;
cout<<"Infantry - attack()"<<endl;
}
demo.cpp
#include <iostream>
#include <stdlib.h>
#include "Infantry.h"
using namespace std;
int main()
{
Soldier s1;
s1.work();
//s1.play();会报错:protecd对于类外部来说就相当于private,在soldier类里面的成员函数可以访问play(),但在类的外部就不行,就好像在主程序中不能直接访问soldier里面的成员变量m_iAge(m_iAge也是protected)
cout<<endl;
Infantry I1;
I1.attack();
system("pause");
return 0;
}
运行结果
Jim
20
Soldier - work
Jerry
Infantry - attack()
请按任意键继续. . .
3-5 练习
3-6 巩固练习
定义两个类,人类中含有数据成员姓名(m_strName)及成员函数eat();
士兵类从人类派生,含有数据成员编号(m_strCode)及成员函数attack();
在main函数通过对数据的访问,体会公有继承的语法特点。
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
/**
* 定义人的类: Person
* 数据成员姓名: m_strName
* 成员函数: eat()
*/
class Person
{
public:
string m_strName;
void eat()
{
cout << "eat" << endl;
}
};
/**
* 定义士兵类: Soldier
* 士兵类公有继承人类: public
* 数据成员编号: m_strCode
* 成员函数: attack()
*/
class Soldier:public Person
{
public:
string m_strCode;
void attack()
{
cout << "fire!!!" << endl;
}
};
int main(void)
{
// 创建Soldier对象
Soldier soldier;
// 给对象属性赋值
soldier.m_strName = "Jim";
soldier.m_strCode = "592";
// 打印对象属性值
cout << soldier.m_strName << endl;
cout << soldier.m_strCode << endl;
// 调用对象方法
soldier.attack();
soldier.eat();
return 0;
}
运行结果
Jim
592
fire!!!
eat