vector 不会推送 class 函数 c++

vector wont push class function c++

我正在尝试制作一款文字冒险类游戏,我想避免一堆条件语句,所以我正在尝试学习 classes 的东西等等。我已经创建了几个 classes,但唯一与此问题相关的是选项 class 和项目 class。 我的问题是我正在尝试 push_back() 一个对象到该对象的 class 类型的向量中,但显然直到尝试向量时它才会运行待访问。此行在 main.cpp 中。我研究过这个,但我一直没能找到直接的答案,可能是因为我没有足够的经验,一开始就不知道答案。

程序分为 3 个文件,main.cpp、class.h 和 dec.cpp。 dec.cpp 声明 class 个对象并定义它们的属性等等。

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"和它的属性,我试过直接push成功了,名字显示出来了。

class.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

如有任何帮助,我们将不胜感激!我意识到整个结构可能需要更改,但我认为即使是这种情况,这个答案也会有所帮助。

My problem is that I am trying to push_back() a object into a vector of the type of that object's class and it apparently doesn't happen yet runs until the vector is attempted to be accessed.

它发生了,但只发生在你的 setinvent 方法中:

void Option::setinvent(string a, vector<Item> Inventory, Item d)
                                 ^^^^^^^^^^^^ - passed by value

库存是按值传递的,这意味着它是setinvent函数中的一个局部向量变量。如果要从main函数修改vector,请将其作为参考:

void Option::setinvent(string a, vector<Item>& Inventory, Item d)
                                 ^^^^^^^^^^^^ - passed by reference, modifies vector from main

现在库存是局部参考变量。也不要忘记更改头文件中的 setinvent 声明。