As I currently study Java in University but I am working on a C++ project. It is a text game in which I'm trying to create an empty vector of Item objects which I'm later going to add with the addItem(Item newItem) method of the Room object. The problem is that when in the constructor I try to set it so that every time a room is created, a new vector of Item objects is created with a capacity of the vector of 20, it gives me this error:
'Item::Item': no appropriate default constructor available
Here is the code:
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;
}