c++ - 具有抽象成员的对象(无指针)

标签 c++ pointers polymorphism

我有以下类(class),

class Simulation {
public:
  btDefaultCollisionConfiguration collisionConfiguration;
  btBroadphaseInterface broadphase;
  btSequentialImpulseConstraintSolver solver;
  btDynamicsWorld dynamicsWorld;

  Simulation() {
    broadphase = btCollisionDispatcher(&collisionConfiguration);
  }
}

当我编译时出现这个错误

cannot declare field ‘Simulation::broadphase’ to be of abstract type ‘btBroadphaseInterface’

现在我想我知道我做错了什么。如果这个编译然后我调用构造函数的那一刻分配的内存将是一个虚拟类并且不会包含子类(btCollisionDispatcher)。我知道如何用指针解决这个问题,但我一直听人说你应该在 C++ 中避免使用指针,我想我会试一试。到目前为止,我一直很成功,但我不知道该怎么做。

最佳答案

是的,你只能有指向抽象类的指针或引用,因为你不能实例化一个抽象类,因为根据定义,它有一个“不完整”的定义(不要按字面意思理解)。这只是一个界面。

如果你想避免指针,你可以使用引用,像这样:

class Simulation {
public:
  btDefaultCollisionConfiguration collisionConfiguration;
  btBroadphaseInterface& broadphase;
  btSequentialImpulseConstraintSolver solver;
  btDynamicsWorld dynamicsWorld;

  Simulation() : broadphase(someFunctionThatReturnsAbtBroadphaseInterfaceReference()) {

  }
}

或者像这样的智能指针:

// header for shared_ptr
#include <memory>

class Simulation {
public:
  btDefaultCollisionConfiguration collisionConfiguration;
  shared_ptr<btBroadphaseInterface> broadphase;
  btSequentialImpulseConstraintSolver solver;
  btDynamicsWorld dynamicsWorld;

  Simulation() : broadphase(someFunctionThatReturnsAbtBroadphaseInterfacePointerOrSmartPointer()) {

  }
}

关于c++ - 具有抽象成员的对象(无指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7380888/

相关文章:

c++ - 将 unsigned [char, short, int, long] 转换为 double 的结果不一致

C 指向字符串数组的指针

c - 指向字符串的指针以及赋值和取消引用之间的区别

c++ - 如何从内存中删除动态添加的节点?

c++ - C++中的子类型多态性

java - 我可以将枚举作为变量传递和使用吗?

Java集合——元素的多态访问

c++ - 如何使用 Makevars 链接到 RCPP 中已编译的外部共享库?

c++ - Qt 多语言应用程序

c++ - .IsA 在 Python 中的含义