#include <iostream>
using namespace std;
//Peasant继承自Human,Human继承自CRE
//基类,生物类
class CRE
{
//成员变量
private:
int HP; //生命值
//这里曾把DEF写成DET
int DEF; //防御
int ACT; //攻击
public:
//构造函数
CRE(int h = 100,int d = 100, int a = 100):HP(h),DEF(d),ACT(a)
{
cout << "CRE(i,i,i)," << this << endl;
}
//析构函数
~CRE()
{
cout << "~CRE(), " << this << endl;
}
//成员函数:
int getHP()
{
return HP;
}
void setHP(int HP)
{
this->HP = HP;
}
int getDEF()
{
return DEF;
}
int getACT()
{
return ACT;
}
void move()
{
cout << "CRE is moving " << endl;
}
void attack()
{
cout << "CRE is attacking " << endl;
}
};
class Human : public CRE
{
//构造函数
public:
//冒号后的CRE的小伙号里的小括号里写了参数就调用有参的构造函数,没有写的话就调用空参的
Human(int h = 100, int d = 100, int a = 100):CRE(h,d,a)
{
cout << "Human(), " << this << endl;
}
//析构函数
~Human()
{
cout << "~Human(), " << this << endl;
}
//成员函数
//
};
class Peasant : public Human
{
//这里曾经忘了写public
public:
//构造函数
Peasant(int h = 50,int d = 20, int a = 10):Human(h,d,a)
{
cout << "work work ..." << this << endl;
}
//析构函数
~Peasant()
{
cout << "OH,I'll dead." << this << endl;
}
//成员函数
//名字隐藏,函数名和父类的相同。只要函数名相同就会隐藏,不管一个是不是有参另一个是不是无参。那返回值又关么?别问,自己试一试。
void move()
{
cout << "Peasant move " << endl;
}
//名字隐藏
void attack(string name)
{
cout << "Peasant attacked" << name << endl;
}
//名字隐藏
void work()
{
cout << " Mork work " << endl;
}
};
int main()
{
//Human对象h
Human h;
h.move();
h.attack();
cout << h.getHP() << endl;
cout << "==========" << endl;
//Peasant对象p1
Peasant p1;
p1.move();
p1.attack("MK");
//发生了名字隐藏,积累的无参函数被隐藏了,于是调用的是子类的attack的有参函数,因此括号里必须传递参数
p1.Human::attack();
p1.work();
p1.Human::move(); //调用父类中继承来的
cout << "==========" << endl;
}
/* 一次运行结果
CRE(i,i,i),0x7fffe8703670
Human(), 0x7fffe8703670
CRE is moving
CRE is attacking
100
==========
CRE(i,i,i),0x7fffe8703660
Human(), 0x7fffe8703660
work work ...0x7fffe8703660
Peasant move
Peasant attackedMK
CRE is attacking
Mork work
CRE is moving
==========
OH,I'll dead.0x7fffe8703660
~Human(), 0x7fffe8703660
~CRE(), 0x7fffe8703660
~Human(), 0x7fffe8703670
~CRE(), 0x7fffe8703670
*/
继承、名字隐藏
最新推荐文章于 2024-02-03 14:26:48 发布