如何在课堂中使用struct

how to use struct in a class

本文关键字:struct 课堂      更新时间:2023-10-16

lifeform.h

class lifeform
{
  public:
    struct item;
    void buyItem(item &a);
   //code..
}; 

lifeform.cpp

struct lifeform::item
{
std::string type,name;
bool own;
int value,feature;
    item(std::string _type,std::string _name,int _value,int _feature):type(_type), name(_name),value(_value),feature(_feature)
     {
        own=false;
     }
};
lifeform::item lBoots("boots","Leather Boots",70,20);
void lifeform::buyItem(item &a)
{
if(a.own==0)
{
    inventory.push_back(a);
    a.own=1;
    addGold(-a.value);
    std::cout << "Added " << a.name << " to the inventory.";
    if(a.type=="boots")
    {
        hp-=inventory[1].feature;
        inventory[1]=a;
        std::cout << " ( HP + " << a.feature << " )n";
        maxHp+=a.feature;
        hp+=a.feature;
    }
    }

到目前为止还没有错误,但是当我想在main.cpp中使用它们时

 #include "lifeform.h"
 int main()
 {
 lifeform p;
 p.buyItem(lBoots);
 }

编译器说我[错误]'lboots'在此范围中没有声明,但我宣布了我的课程,我错过了什么?

要使用您的lifeform::item lBoots,您需要以主要声明:

#include "lifeform.h"
extern lifeform::item lBoots; // <-- you need this.
int main()
{
    lifeform p;
    p.buyItem(lBoots);
}

或或者,您应该将extern lifeform::item lBoots;放在lifeform.h中。