| bdwg (4) | |
|
I have two problems. 1. I would like to make a vector with initial length, say 10, within a class. The vector's elements are from another class. Class Player { public: vector<Item> Inventory(10); }; The error message is "Expected a ')'" as if it should only be vector<Item> Inventory(); The code I've written for such is below. This is the file "Header.h" #ifndef Item_Test_Header_h #define Item_Test_Header_h #include <vector> #include "Item.h" #include <string> using namespace std; class Player { public: vector<Item> Inventory(10); }; #endif This is the file "Item.h" #ifndef Item_Test_Item_h #define Item_Test_Item_h #include <string> using namespace std; class Item { public: string name; Item() { name= "N/A"; } }; #endif 2. My second problem is that I would like to access the elements of this vector within my main function. At first, I didn't declare any initial size of my Inventory vector. It was simply vector<Item> Inventory; and I tried accessing the elements in my main file by Player MC; Item Ptn; Ptn.name= "Potion"; MC.Inventory[1]= Ptn; cout<< Mc.Inventory[1].name; Using cout just to check if it works, but the console displays "(lldb)" The code for such follows. #include <iostream> #include "Header.h" #include "Item.h" #include <string> using namespace std; int main() { Item Ptn; Ptn.name= "Potion"; Player MC; MC.Inventory[0]= Ptn; cout<< MC.Inventory[0].name; int end; cin>> end; return 0; } | |
|
|
|
| Zhuge (2974) | |
Declare it as vector<Item> Inventory;, then use an initializer list in the Player constructor to call the Inventory constructor.
| |
|
|
|
| bdwg (4) | |
|
Thanks! For anyone who this might help: To fix it, in the constructor I wrote Player() : Inventory(10) { } | |
|
|
|