使用了未定义的类_解决方法

在游戏类的编写中,遇到了一个导入工程后运行出现”使用了未定义的类“的错误。

绞尽脑汁也没搞懂是哪里出现了问题,看了其他人的blog后才发现了问题所在:定义顺序

第一次错误代码如下:

class Hp : public res{
private:
	int hpValue;		//the value of hp this kind of medicine can provide;
	int number;			//the number of the kind of medicine that people has;
public:
	Hp(){
	}
	
	void setHpValue(int value){
		hpValue = value;
	}
	
	Hp(int value, string _name){
	    type = 1;				//define the type is hp;
		hpValue = value;		//define the value of hp provided;
		name = _name;			//define the name of the medicine;
		number = 0;				//define the number of the medicine(initialized);
	}
	
	int getType(){
		return type;			//get the type of the medicine;
	}

	void used(Person &person){
		person.addHp();
	}

	void sub(int _number){
		number -= _number;      //subcline number medicines;
	}

	void add(int _number){
		number += _number;      //add the number medicines;
	}

	int getNumber(){
		return number;	        //return the number of the medicine;
	}

	void setNumber(int value){
		number = value;			//set the number of the medicine;
	}
};
class Person{
a function with Hp parament;
};


有代码可以看出来,在hp类中使用到了person类,而在person类中也使用到了hp类,所以出现的定义问题。但是要怎么解决呢?

第一次修改,知道了类定义可以先声明的说法后,在第一排添加了 class Person;


可是,还是失败,于是乎,看见了某大佬的blog,发现原来在类中只要涉及到还没有实现的类的函数,也要先声明,然后在类的最后实现,于是,最后改为

class Person;
class Hp : public res{
private:
	int hpValue;		//the value of hp this kind of medicine can provide;
	int number;			//the number of the kind of medicine that people has;
public:
	Hp(){
	}
	
	void setHpValue(int value){
		hpValue = value;
	}
	
	Hp(int value, string _name){
	    type = 1;				//define the type is hp;
		hpValue = value;		//define the value of hp provided;
		name = _name;			//define the name of the medicine;
		number = 0;				//define the number of the medicine(initialized);
	}
	
	int getType(){
		return type;			//get the type of the medicine;
	}

	void used(Person &person);

	void sub(int _number){
		number -= _number;      //subcline number medicines;
	}

	void add(int _number){
		number += _number;      //add the number medicines;
	}

	int getNumber(){
		return number;	        //return the number of the medicine;
	}

	void setNumber(int value){
		number = value;			//set the number of the medicine;
	}
};
class Person{};

void Hp::used(Person &person){
		person.addHp(hpValue);  //add the hp of the person;
		sub(1);					//the number of the medicine subcline 1;
}
于是乎,成功了!
©️2020 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值