如何在 C++ 中创建一个空的对象向量?

时间:2020-12-28 22:56:21

标签: c++ class oop object vector

因为我目前在大学学习 Java,但我正在从事 C++ 项目。这是一个文本游戏,我试图在其中创建一个空的 Item 对象向量,稍后我将使用 Room 对象的 addItem(Item newItem) 方法添加该向量。问题是,当我在构造函数中尝试设置它时,每次创建房间时,都会创建一个容量为 20 的 Item 对象的新向量,它给了我这个错误:

'Item::Item':没有合适的默认构造函数可用

代码如下:

Item.hpp:

#include <iostream>
#include <string>

#ifndef Item_HPP
#define Item_HPP

class Item {

    std::string description;

public:
    Item(std::string description);
    std::string getDescription();
    void setDescription(std::string description);
    void use();
};

#endif

Item.cpp:

#include "Item.hpp"

Item::Item(std::string description) {

    this->description = description;
}

std::string Item::getDescription() {

    return this->description;
}

void Item::setDescription(std::string description) {

    this->description = description;
}

void Item::use() {

    std::cout << "You are using item: " << description << std::endl;
}

Room.hpp:

#include <iostream>
#include <string>
#include <vector>
#include "Item.hpp"

#ifndef Room_HPP
#define Room_HPP


class Room {

    std::string description;
    static const int MAX_ITEMS = 20;
    std::vector <Item> items;
    int numberOfItems;


public:
    Room(std::string description);
    std::string getDescription();
    void addItem(Item newItem);
    std::vector<Item> getItems();

    Item getItem(std::string description);
};

#endif

Room.cpp:

#include "Room.hpp"

Room::Room(std::string description) {

    this->description = description;
    this->items = std::vector<Item>(20);
    this->numberOfItems = 0;
}

std::string Room::getDescription() {

    return this->description;
}

void Room::addItem(Item newItem) {

    if (numberOfItems < MAX_ITEMS) {
        this->items[numberOfItems] = newItem;
        numberOfItems++;
    }
}

std::vector<Item> Room::getItems() {

    return this->items;
}

Item Room::getItem(std::string description) {

    int i = 0;
    bool found = false;
    Item *target = NULL;
    while (!found && i < numberOfItems) {

        if (items[i].getDescription() == description) {

            target = &items[i];
            found = true;
        }
        ++i;
    }
    return *target;
}

1 个答案:

答案 0 :(得分:0)

您可以首先为 20 个元素只缓存 reserve(),然后通过 push_back() 添加元素。

Room::Room(std::string description) {

    this->description = description;
    this->items = std::vector<Item>();
    this->items.reserve(20);
    this->numberOfItems = 0;
}

void Room::addItem(Item newItem) {

    if (numberOfItems < MAX_ITEMS) {
        if (numberOfItems == static_cast<int>(this->items.size())) {
            this->items.push_back(newItem);
        } else if (numberOfItems < static_cast<int>(this->items.size())) {
            this->items[numberOfItems] = newItem;
        } else {
            // unsupported to create gap between items
        }
        numberOfItems++;
    }
}
相关问题