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

来源:互联网 发布:淘宝老顾客回购率 编辑:程序博客网 时间:2024/05/20 06:51

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

绞尽脑汁也没搞懂是哪里出现了问题,看了其他人的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;}
于是乎,成功了!

原创粉丝点击