0

我无法弄清楚如何通过指向对象的指针数组访问 bject 方法。

我有一个Environment 类的env对象:

Environment env;

我的环境有一些对象指针以及一个动态的指针数组:

    static Robot *robot;
    static Obstacle *obstacle;
    static Object **objects;

所以在物体内部我可以有机器人和障碍物:

但是现在当我想访问对象数组中对象的方法时,我该怎么做呢?我试过了

    Environment env;
    Robot *robot;

    robot = env.objects[0];
    robot->setSpeed(175);

但它没有用。我收到一个错误:

error: invalid conversion from ‘Object*’ to ‘Robot*’

我究竟做错了什么?

PS:Robot 继承自 Object。

先感谢您!

4

6 回答 6

4

Since Robot inherits from Object you have to use either static_cast or dynamic_cast to cast the pointer:

robot = static_cast<Robot*>(Environment::objects[0]);

As a side note, I also recommend you to use std::vector instead of the array, and a smart pointer like std::shared_ptr instead of the raw pointers.

于 2012-11-03T20:08:05.960 回答
2

You need to cast the Object* to a Robot*. Assuming Robot inherits from Object. I advise you to use dynamic_cast:

Robot* robot = dynamic_cast<Robot*>(env.objects[0]);
if (robot != NULL) {
    robot->setSpeed(14);
}
于 2012-11-03T20:06:06.973 回答
1

You should cast your object from Object* to Robot*. However, you have to make sure it is a Robot object otherwise your application will crash.

Here is an example:

#include <iostream>
class Object
{
};

class Robot : public Object
{
  public:
  int speed;
  void setSpeed(int newSpeed){ speed = newSpeed; }
};

int main()
{
  Object* obj = new Robot();
  ((Robot*)obj)->setSpeed(4);
  std::cout << "Speed is: " << ((Robot*)obj)->speed << std::endl;
}
于 2012-11-03T20:04:47.170 回答
1

You can't implicitly assign pointer of base class to pointer of derived class. If you need to do this, use dynamic_cast.

于 2012-11-03T20:08:28.813 回答
1

objects is declared with type Object**, which means that objects[0] is of type Object*. You cannot assign an Object* to a Robot*. Assuming Robot is a class derived from Object and has at least one virtual member function, you can do

robot = dynamic_cast<Robot*>(object[0]);

This will perform the cast, or set robot to the null pointer value if object[0] happens to not be a Robot. If you know for certain that it is a Robot, you can use static_cast() instead.

于 2012-11-03T20:09:09.750 回答
0

your object does not seem to be a Robot* or a pointer to a subclass of it.

于 2012-11-03T20:05:49.390 回答