【发布时间】:2015-12-17 17:00:07
【问题描述】:
我正在尝试制作一款文字冒险类的游戏,并且我想避免使用一堆条件,所以我正在尝试了解类的东西等等。我创建了几个类,但与此问题相关的唯一类是 Options 类和 Items 类。 我的问题是我正在尝试将一个对象 push_back() 放入该对象类的类型的向量中,并且它显然不会发生,直到尝试访问该向量时才会运行。该行在 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
任何帮助将不胜感激!我意识到可能需要更改整个结构,但我认为即使是这种情况,这个答案也会有所帮助。
【问题讨论】:
-
您忘记通过引用传递向量。
-
它确实 push_back 但是你通过传递值来丢弃结果。
-
感谢您的快速回复!你能告诉我我会在哪里做吗?我不确定如何通过引用传递它。
-
在
void Option::setinvent(string a, vector<Item> Inventory, Item d)中,您必须通过Inventory传递&以获得您需要的行为。你应该通过const&传递a和d所以它应该是:void Option::setinvent(string const& a, vector<Item>& Inventory, Item const& d) -
#include "dec.cpp"在一个非常奇怪的地方;没有什么是不可能的,但您也可能还不太了解头文件。如果是故意的,请检查或评论澄清
标签: c++ class vector push-back