vector不会推送类函数c++

vector wont push class function c++

本文关键字:类函数 c++ vector      更新时间:2023-10-16

我正试图制作一款文本冒险游戏,我想避免使用一堆条件语句,所以我正在努力学习类的东西等等。我已经创建了几个类,但与这个问题相关的只有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声明。