This question already has answers here:
Dealing with circular inclusion in a parent/child class relationship

(2个答案)


5年前关闭。




以下结构应将shared_ptr保留给抽象基类(Shape)。但是,当我尝试编写此代码时,我得到error C2065: 'Shape' : undeclared identifier

所以我知道我不能创建Shape的实例,只能创建派生的Spheres,Boxes等的实例。但是为什么不能对一个抽象基类使用shared_ptr?
#include <memory>  // std::shared_ptr

#include "shape.hpp"

struct Hit {
    // …

    std::shared_ptr<Shape> m_shape;  // Shape that was hit
};

应该注意的是,Shape类确实在使用Hit结构,反之亦然。

最佳答案

用转发声明替换上面的#include "shape.hpp"class Shape;(取决于如何声明struct Shape;,您可能需要Shape)。

这是可能的,因为可以使用不完整的类型声明std::shared_ptr类型的类成员。

这有助于您解开圆形夹杂物。当然,定义struct Hit功能的源文件将需要#include shape.hpp

关于c++ - shared_ptr到抽象基类(成员变量)是一个未声明的标识符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32014093/

10-11 22:59
查看更多