如何在课堂中使用struct
how to use struct in a class
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
中。
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- C++Union/Struct位域的实现和可移植性
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 错误:"Left of getValue must have class/struct/union"
- 在 SVM-Struct 中未定义对 sqrt 的引用(已使用 -lm)
- 数据类型"struct seq<0, 1, 2>{}"含义是什么?
- 附加使用 Struct 作为"multikey"并将 std::vector 用作映射值的映射
- QML/C++/QObject Struct Copy
- 如何在 cpp 中解压缩数字,如果它们是使用 struct.pack(fmt, v1, v2, ..) 打包在 pyth
- Msgpack能否提供更好的性能和与Python的struct.pack()相同的功能?
- 将向量传递给<struct> Lua 表
- MPI_DOUBLE_INT and C++ struct
- C++ 中的"template <typename From, typename Tag> struct Alias;"是什么?
- 如何使用Struct打印交换函数
- 返回类型为struct的函数每次调用时都不返回任何内容
- 对struct::struct的未定义引用是什么意思
- 如何在课堂中使用struct