继承、名字隐藏

#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
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值