继承示例:
1、公有继承示例
#include <iostream>
#include <string>
using namespace std;
//Person类
class Person {
public:
Person();
void play();
protected:
string m_strName;
};
Person::Person()
{
m_strName = "Marry";
}
void Person::play()
{
cout << "Person--play" << endl;
cout << m_strName << endl;
}
//Soldier类
class Soldier: public Person {
public:
Soldier();
void work();
protected:
int m_iAge;
};
void Soldier::work()
{
m_strName = "jim";
m_iAge = 20;
cout << m_strName << endl;
cout << m_iAge << endl;
cout << "soldier--work()" << endl;
}
int main(void)
{
Soldier soldier;
soldier.work();
soldier.play();
system("pause");
return 0;
}
打印结果:
2、保护继承示例:
#include <iostream>
#include <string>
using namespace std;
//Person类
class Person {
public:
Person();
void play();
protected:
string m_strName;
};
Person::Person()
{
m_strName = "Marry";
}
void Person::play()
{
cout << "Person--play" << endl;
cout << m_strName << endl;
}
//Soldier类
class Soldier: protected Person {
public:
Soldier();
void work();
protected:
int m_iAge;
};
void Soldier::work()
{
m_strName = "jim";
m_iAge = 20;
cout << m_strName << endl;
cout << m_iAge << endl;
cout << "soldier--work()" << endl;
}
//Infantry类
class Infantry:public Soldier {
public:
void attack();
};
void Infantry::attack()
{
m_strName = "Tom";
cout << m_strName << endl;
cout << "Infantry--attack()" << endl;
}
int main(void)
{
Infantry infantry;
infantry.attack();
system("pause");
return 0;
}
打印结果:
3、私有继承示例:
#include <iostream>
#include <string>
using namespace std;
//Person类
class Person {
public:
Person();
void play();
protected:
string m_strName;
};
Person::Person()
{
m_strName = "Marry";
}
void Person::play()
{
cout << "Person--play" << endl;
cout << m_strName << endl;
}
//Soldier类
class Soldier: private Person {
public:
Soldier();
void work();
protected:
int m_iAge;
};
void Soldier::work()
{
m_strName = "jim";
m_iAge = 20;
cout << m_strName << endl;
cout << m_iAge << endl;
cout << "soldier--work()" << endl;
}
//Infantry类
class Infantry:public Soldier {
public:
void attack();
};
void Infantry::attack()
{
m_strName = "Tom";
cout << m_strName << endl;
cout << "Infantry--attack()" << endl;
}
int main(void)
{
Infantry infantry;
infantry.attack();
system("pause");
return 0;
}
打印报错结果: