Dec 29, 2012 at 8:03pm Dec 29, 2012 at 8:03pm UTC
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;
}
Dec 29, 2012 at 8:11pm Dec 29, 2012 at 8:11pm UTC
Declare it as vector<Item> Inventory;
, then use an initializer list in the Player constructor to call the Inventory constructor.
Dec 30, 2012 at 3:14am Dec 30, 2012 at 3:14am UTC
Thanks! For anyone who this might help: To fix it, in the constructor I wrote
Player() : Inventory(10)
{
}