c++ - 如何在类中使用结构

标签 c++ class struct

生命体.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/

相关文章:

c - 返回寄存器中的结构 - GCC 中的 ARM ABI

c++ - 英特尔 SGX 错误 : What does the 8207 error mean when I cannot load the enclave correct

c++ - C++ EXC_BAD_INSTRUCTION?

Java:为类的所有实例设置 boolean 值

涉及 ; 的结构数组的编译错误代币

c - 指向结构体的指针数组

C++ 与 Fortran 并行 MM 速度差异循环平铺

c++ - 无法使用 UNICODE 读取文件(存在)

c++ - 无效删除指向类的指针

java - 如何使用调用该方法的类的名称创建一个 .txt 文件?