生命体.h
class lifeform
{
public:
struct item;
void buyItem(item &a);
//code..
};
生命体.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
,你需要在main中声明它:
#include "lifeform.h"
extern lifeform::item lBoots; // <-- you need this.
int main()
{
lifeform p;
p.buyItem(lBoots);
}
或者您应该将 extern lifeform::item lBoots;
放在您的 lifeform.h
中。
关于c++ - 如何在类中使用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43498539/