Эй, я использую вектор плюс его итератор. У меня есть это в файле Inventory.h вместе с Inventory.cpp. Я хочу знать, могу ли я вызвать его напрямую, чтобы получить доступ к функциям векторной библиотеки, таким как push, pop и т. Д. Потому что на данный момент я не могу. Может кто-то помочь мне с этим.
Вот мой код:
Inventory.h
//-------------------------------------------------------------------------------
// Inventory.h
//-------------------------------------------------------------------------------
#ifndef INVENTORY_H
#define INVENTORY_H
#include <string>
#include <vector>
using namespace std;
class Inventory
{
public:
//Constructor
Inventory();
//Methods.
string add(string item);
void displayInventory();
void showInventory();
private:
//Data members
vector<string> inventory;
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
};#endif //INVENTORY_H
Inventory.cpp
#include "Inventory.h"#include <iostream>
#include <vector> // To enable the use of the vector class.
#include <string>using namespace std;Inventory::Inventory()
{
}
string Inventory :: add(string item)
{
inventory.push_back(item);
return item;
}
void Inventory:: showInventory()
{
char input[80];
cin >> input;
char inventoryRequest[] = "i";
int invent = strcmp (input,inventoryRequest);
//compare the player input to inventoryRequest (i) to see if they want to look at inventory.
if(invent == 0)
{
displayInventory();
}}
void Inventory:: displayInventory()
{
//vector<string> inventory;
cout<< "You have " << inventory.size() << " items.\n";
cout << "\n******Inventory******";
cout<< "\nYour items:\n";
for (int i= 0; i< inventory.size(); ++i)
cout<< inventory[i] << endl;
}
Что я хочу быть в состоянии сделать:
int main()
{
Inventory inventory;
inventory.push_back();}
ошибки
Error 2 error LNK2019: unresolved external symbol "public: class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > & __thiscall Inventory::GetContainer(void)" (?GetContainer@Inventory@@QAEAAV?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@XZ) referenced in function _main C:\Users\Conor\Documents\College\DKIT - Year 2 - Repeat\DKIT - Year 2 - Semester 1 - Repeat\Games Programming\MaroonedCA2\MaroonedCA2\Main.obj MaroonedCA2
Error 3 error LNK1120: 1 unresolved externals C:\Users\Conor\Documents\College\DKIT - Year 2 - Repeat\DKIT - Year 2 - Semester 1 - Repeat\Games Programming\MaroonedCA2\Debug\MaroonedCA2.exe MaroonedCA2
Простое решение — добавить push_back
и другие векторные методы, которые вы хотите скопировать в свой класс инвентаря:
class Inventory
{
public:
//Constructor
Inventory();
//Methods.
std::string add(std::string item);
void displayInventory();
void showInventory();
void push_back(const std::string& s) { inventory.push_back(s); }
private:
//Data members
std::vector<std::string> inventory;
std::vector<std::string>::iterator myIterator;
std::vector<std::string>::const_iterator iter;
};
Обратите внимание, что наследование в частном порядке от std::vector
также может быть вариантом. Это не на 100% безопасно, но трудно найти сценарии, в которых это может создать проблему. Наследовать публично — это определенно нет-нет. Этот пример показывает, как выставить часть std::vector
Частный унаследованный публичный интерфейс:
class Inventory : private std::vector<std::string>
{
public:
// make a selection of the vector's methods public for this class.
using std::vector<std::string>::push_back;
using std::vector<std::string>::pop_back;
using std::vector<std::string>::begin;
using std::vector<std::string>::end;
};
Вы можете наследовать наш класс от std :: vector:
class Inventory : public std::vector<std::string> {
public:
Inventory();
void displayInventory();
void showInventory();
// [...]
}
Тогда в вашем коде вы сможете делать такие вещи, как:
int main()
{
Inventory inv;
inv.push_back("item 1");
inv.push_back("item 2");
for (Inventor::iterator it = inv.begin(); it != inv.end(); ++it)
std::cerr << *it << ' ';
std::cerr << std::endl;
}
Благодаря наследованию вы можете избежать переопределения методов, итераторов и так далее.
В этом фрагменте кода есть много проблем / областей улучшения. Тем не менее, для конкретной, которую вы спросили, обратите внимание, что push_back не является функцией-членом класса Inventory. Итак, вы получаете ошибку компилятора.
Для этого вам нужно позвонить на инвентарь.