Изменение значения элемента в объекте, который хранится в векторе в другом объекте через внешнюю функцию в C ++ - PullRequest
0 голосов
/ 02 декабря 2018

Таким образом, создан класс под названием «Предмет», и объект этого класса будет иметь 100% -ное условие при запуске. Игрок сохраняет предметы (с именем «яблоко» в данном случае) всякий раз, когда я говорю ему об этом.В функции degradeT я хочу передать весь вектор, содержащий предметы, которые игрок забрал, и затем изменить условие каждого предмета в этом векторе на -1 через функцию chCond.

первая ошибка:

initial value of reference to non-const must be an lvalue

вторая ошибка:

'void degradeT(std::vector<Item,std::allocator<_Ty>> &)': cannot convert argument 1 from 'std::vector<Item,std::allocator<_Ty>>' to 'std::vector<Item,std::allocator<_Ty>> &'
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>

using std::cout; using std::cin; using std::endl;
using std::string; using std::vector; using std::to_string;

class Item {

private:
    string name; // Item name
    float condition; // Item condition
    bool consumable; // Is the item consumable
public:
    Item() {}
    Item(string a, float b, bool c) { name = a; condition = b; consumable = c; }
    Item(string a, bool c) { name = a; condition = 100.f; consumable = c; }

    string getName() {
        return name;
    }
    float getCond() {
        return condition;
    }
    bool isCons() {
        return consumable;
    }
    void chCond(float a) { // Change Item condition
        condition += a;
    }
};

//-----------------------

class Player {

private:
    vector<Item> plItems; // Item container
public:
    Player() {}

    void pickUpItem(Item a) { // Adding Items to inventory
        plItems.push_back(a);
        cout << a.getName() << " added to inventory!\n";
    }
    void checkItemConds() { // Checking condition of all items
        for (unsigned int a = 0, siz = plItems.size(); a < siz; a++) {
            cout << plItems[a].getName() << "'s condition is: " << plItems[a].getCond() << "%\n";
        }
    }
    Item returnItem(unsigned int a) { // Return a specific Item
        return plItems[a];
    }
    int getCurInvOcc() { // Get cuurent inventory occupation
        return plItems.size();
    }
    vector<Item> getPlItems() { // Return the vector (Item container)
        return plItems;
    }
};

//-------------------------
void degradeT(vector<Item>& Itemss); // Degrade item after some time
//-------------------------

int main()
{
    Player me; // me
    string inp; // input
    int num = 1; // apple 1, apple 2, apple 3...

    while (inp != "exit") {
        cin >> inp;

        if (inp == "addApple") {
            Item apple(("apple " + to_string(num)), true);
            me.pickUpItem(apple);
            num++;
        }

        if (inp == "checkItemConds") {
            me.checkItemConds();
        }

        if (inp == "timeTick") {

            // This doesn't have anything to do with time I just want to test the function manually

            degradeT(me.getPlItems());
        }

    }

    system("PAUSE");
    return 0;
}

void degradeT(vector<Item> &Itemss) {

    for (unsigned int a = 0, siz = Itemss.size(); a < siz; a++) {
        Itemss[a].chCond(-1);
        cout << Itemss[a].getName() << endl;
    }
}

1 Ответ

0 голосов
/ 02 декабря 2018

Я не уверен, что ваш вопрос, но ваша ошибка связана с функцией void degradeT(vector<Item> & Itemss).

Эта функция ожидает ссылку, но вы передаете r-значение.Вы можете либо вернуть ссылку с помощью getPlItems(), либо передать значение l в degradeT.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...