vector不会推送类函数c++
vector wont push class function c++
我正试图制作一款文本冒险游戏,我想避免使用一堆条件语句,所以我正在努力学习类的东西等等。我已经创建了几个类,但与这个问题相关的只有Options类和Items类我的问题是,我正试图将一个对象推入该对象类类型的向量中,但在尝试访问该向量之前,它显然还没有运行。这一行在main.cpp中。我对此进行了研究,但一直未能找到直接的答案,可能是因为我的经验不足,一开始就不知道答案。
该程序分为3个文件,main.cpp、class.h和dec.cpp。dec.cpp声明类对象并定义它们的属性等等。
main.cpp:
#include <iostream>
#include "class.h"
using namespace std;
#include <vector>
void Option::setinvent(string a, vector<Item> Inventory, Item d)
{
if (a == op1)
{
Inventory.push_back(d);
}
else {
cout << "blank";
}
return;
}
int main()
{
vector<Item> Inventory;
#include "dec.cpp"
Option hi;
hi.op1 = "K";
hi.op2 = "C";
hi.op3 = "L";
hi.mes1 = "Knife";
hi.mes2 = "Clock";
hi.mes3 = "Leopard!!";
string input1;
while (input1 != "quit")
{
cout << "Enter 'quit' at anytime to exit.";
cout << "You are in a world. It is weird. You see that there is a bed in the room you're in." << endl;
cout << "There is a [K]nife, [C]lock, and [L]eopard on the bed. Which will you take?" << endl;
cout << "What will you take: ";
cin >> input1;
hi.setinvent(input1, Inventory, Knife);
cout << Inventory[0].name;
cout << "test";
}
}
dec.cpp只是声明了Item"Knife"及其属性,我已经尝试过直接推送,它有效,并且名称显示出来。
h级
#ifndef INVENTORY_H
#define INVENTORY_H
#include <vector>
class Item
{
public:
double damage;
double siz;
double speed;
std::string name;
};
class Player
{
public:
std::string name;
double health;
double damage;
double defense;
double mana;
};
class Monster
{
public:
double health;
double speed;
double damage;
std::string name;
};
class Room
{
public:
int x;
int y;
std::string item;
std::string type;
};
class Option
{
public:
std::string op1;
std::string op2;
std::string op3;
std::string mes1;
std::string mes2;
std::string mes3;
void setinvent(std::string a, std::vector<Item> c, Item d);
};
#endif
如有任何帮助,我们将不胜感激!我意识到整个结构可能需要改变,但我认为即使是这样,这个答案也会有所帮助。
我的问题是,我试图将一个对象推入该对象类类型的向量中,但在尝试访问该向量之前,它显然还没有运行。
它只发生在你的setinvent方法中:
void Option::setinvent(string a, vector<Item> Inventory, Item d)
^^^^^^^^^^^^ - passed by value
存货是通过值传递的,这意味着它是setinvent函数中的一个局部向量变量。如果您想修改主函数中的矢量,请将其作为参考:
void Option::setinvent(string a, vector<Item>& Inventory, Item d)
^^^^^^^^^^^^ - passed by reference, modifies vector from main
现在Inventory是本地参考变量。另外,不要忘记更改头文件中的setinvent声明。
相关文章:
- 如何通过派生类函数更改基类中的向量
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 在类函数中初始化外部作用域变量
- c++ 在非类函数中使用类变量
- SDL_PollEvent() 无法捕获类函数内部SDL_QUIT?
- 从类成员函数到类 C 函数指针的转换
- 如何在模板类函数中分配结构值?
- 有没有办法将重载的类函数绑定到函数对象?
- 启动类函数作为失去引用的线程
- C++调用使用重写函数的父类函数
- 将值传递到另一个类函数在打印时为零
- 计算对类函数的所有调用次数
- 由于签名差异,调用了错误的子类函数
- 使用宏调用类函数
- 虚拟基类函数中派生类的大小
- 模板类/函数中的交叉前向声明
- 在C++中使用非静态类函数的函数
- 无法访问基类函数 C++
- 类函数返回到另一个类函数返回打印不同的值
- C++ 在外部使用嵌套结构实现类函数