3

我正在尝试使用一个类的指针向量。尝试访问 Agent 类的任何成员时,我要么得到错误的指针,要么得到空数据。代码如下。

class Grue : public Agent
{
    string name;
    Room *cur_room;
 public:
   Functions()....
};

class Agent
{
        Room *cur_room;
        string name;
  public:
         Functions()....
};


Grue* Grue1 = new Grue("Test", roompointer);
vector<Agent*> agents;
agents.push_back(Grue1);
4

1 回答 1

4

Data members are private by default in a class. Thus your cur_room, name variables are different in the Agent and Grue class. When you call the Grue constructor, the Grue fields are initialized, but the vector stores Agent pointers, therefor you are accessing the agent fields which are not initialized.

here's the correct way of doing this:

class Agent
{
protected:
    Room *cur_room;
    string name;
public:
    Agent(string n, Room * r)
    : cur_room (r), name(n)         
    {}
};

class Grue : public Agent
{

public:
    Grue(string n, Room * r):Agent(n,r)
    {

    }
};
于 2012-05-26T00:07:19.523 回答