cat.cpp

来自「《游戏编程指南》这是一本很好的游戏开发指导教材,并且附有源代码」· C++ 代码 · 共 55 行

CPP
55 行
字号
#include <iostream>
   	using namespace std;

class THING //定义基类
{
protected:
	int mass,volume;
public:
	THING(int m, int v);
	int get_mass( );
	void set_mass(int new_mass);
};

THING::THING(int m, int v)
{
	mass=m;
	volume=v;
}

int THING::get_mass( )
{
	return mass;
}

void THING::set_mass(int new_mass)
{
	if (new_mass>=0)
		mass=new_mass;
}

class ANIMAL: public THING //定义派生类
{
private:
	int life;
public:
	ANIMAL(int x) : THING(10+x,7) { life=x; };
	//定义派生类的构造函数时需要给出初始化基类的办法
    //如有多个基类,用逗号隔开分别提供参数
	void set_life(int new_life) { if (new_life>=0) life=new_life; }; 
	int get_life( ) { return life; };
	void kill( ) { life=0; };
};

ANIMAL cat(50);


void main( )
{
	cout<<cat.get_mass( )<<endl;  //cat继承了THING类的方法
	cout<<cat.get_life( )<<endl;
	cat.set_life(100); //也有自己的方法
	cat.kill( );
	cout<<cat.get_life( )<<endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?