Hi, I'm C++ beginner, and I'm looking for a solution of the pointer now. I write source code first because my description skills of the English is too bad.(Thank you, google translator!) This is my code example.
#include <iostream>
#include <vector>
using namespace std;
class UNIT
{
public :
struct OBJ
{
float x,y,z;
};
vector<OBJ> obj;
virtual void add(int x,int y,int z)=0;
virtual void size()=0;
};
class KNIGHT : public UNIT
{
public :
struct OBJ
{
float x,y,z;
};
vector<OBJ> obj;
void add(int x,int y,int z)
{
OBJ sample;
sample.x=x;
sample.y=y;
sample.z=z;
obj.push_back(sample);
}
void size()
{
cout << obj.size() << endl;
}
};
int main()
{
KNIGHT knight;
KNIGHT::OBJ sample_knight;
UNIT* pt = &knight;
pt->add(11,22,33);
knight.obj.push_back(sample_knight);
pt->size();
cout << pt->obj.size() << endl;
getchar();
return 0;
}
And result is
2
0
(If I access the KNIGHT's variables likes pt->obj[0].x directly, it cause 'line 932 out of range')
From this experiment, I extracted the following results.
- UNIT* pt didn't point to KNIGHT's vector obj.
- But the UNIT* pt can use KNIGHT's add() and size().
- Probably it is associated with inheritance between UNIT and KNIGHT.
In addition, I'd tried pt->obj.push_back() (In this case, sample is UNIT::OBJ) and print pt->obj.size(), it showed me increased value. But pt->size() was the same as before. I expect it will cause problems of any kind at somewhere, and it is useless because it isn't connected with KNIGHT's add() and size().
So conclusion is this.
How can I get vector<OBJ> of KNIGHT(not UNIT) in directly, with UNIT* pointer or something?
※I'll use this in character pick function.
for example :
struct CHAR_LIST
{
int type,num;
};
UNIT* Select_Unit(int type)
{
switch(type)
{
case CHAR_KNIGHT :
{
return &knight;
}
case CHAR_ARCHER :
{
return &archer;
}
}
}
vector<CHAR_LIST> char_list;
UNIT* pt;
for (int num=0; num<char_list.size(); num++)
{
pt = Select_Unit(char_list[num].type);
pt->obj[char_list[num].num].x+=10;
pt->obj[char_list[num].num].y=0;
}
UNIT::objto access the base class version inside the derived class. (ReplaceUNITwith whatever the base name is, of course)