Array from Class

Jun 6, 2011 at 8:06am
Hi, I'm having trouble with using class objects and converting them into an array... I'm a little new to C++ so please explain to me why I should change something... code:

class Weapon

{
private:
public:

	int element; // elements: None, Fire, Ice, Lightning, Water, Wind, Earth, Light, Dark
	char *name;
	int hpbonus;
	int mpbonus;
	int spbonus;
	int strbonus;
	int defbonus;
	int dexbonus;
	int evabonus;
	int matkbonus;
	int mdefbonus;
	int spdbonus;

};

Weapon woodsword(1, "Wooden Sword", 0. 0, 0, 13, 1, 3, 0, 0, 0, 0, 0);
Last edited on Jun 6, 2011 at 8:06am
Jun 6, 2011 at 8:59am
An array is a fixed sequence of things. You almost certainly don't want an array. The most flexible and similar alternative is a vector--a sequece of things that can change size.

You declare a vector of Weapon with:
 
std::vector<Weapon> weapons;
You add a weapon with:
 
weapons.push_back(woorsword);
You access this first element as follows:
 
std::cout << "First weapon name is: " << weapons[0].name << std::endl;


In your Weapon object, you have an in that represents elements. A more suitable way to handle this is to us an enum:
1
2
3
4
5
6
7
8
9
10
enum Element
{
    ENone, EFire, EIce, ELightning, EWater, EWind, EEarth, ELight, EDark;
};

class Weapon
{
    Element element;
    //...
};
Topic archived. No new replies allowed.