如何在类中使用struct

时间:2017-04-19 14:24:42

标签: c++ class struct

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'没有在这个范围内声明,但是我声明它是类,我错过了什么?

1 个答案:

答案 0 :(得分:1)

要使用lifeform::item lBoots,您需要在main中声明它:

#include "lifeform.h"

extern lifeform::item lBoots; // <-- you need this.

int main()
{
    lifeform p;
    p.buyItem(lBoots);
}

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