从外部访问静态成员并通过继承 c++ 访问静态成员

Accessing static member externally and through inheritance c++

本文关键字:访问 静态成员 继承 c++ 从外部      更新时间:2023-10-16

我有一个类,其中包含一个ID3D11Device成员,我想将其设为static,因为目前,我希望多个Entity类实例访问该ID3D11Device。问题是,我无法访问 Direct3D 类,将ID3D11Device静态成员安置在其对象之外,而无需直接实例化Direct3D类。

由于多个类继承自Direct3D类(为了hwnd详细信息,该类又继承自WindowsClass),我想将其保留为基类,以便访问从Direct3D继承的所有类,如以下示例所示:

class Direct3D: WindowsClass{
public:
    Direct3D();
    ~Direct3D();
    static ID3D11Device* Device;
}

还有一个继承的类:

class EntityType: Direct3D{
public:
    EntityType();
    ~EntityType();
    void SomeDeviceDependentFunction();
}

其中成员定义为:

void EntityType::SomeDeviceDependentFunction(){
//Perform some action calling Direct3D::Device. 
}

请注意,类Direct3D是在 Direct3D.h 中定义的,EntityType是在 EntityType.h 中定义的,依此类推。所以在概念上一切看起来都很肉汁,直到我去编译并收到可怕的错误:

Error 52 error LNK2001: unresolved external symbol "public: static struct ID3D11Device * Direct3d::Device" (?Device@Direct3d@@2PAUID3D11Device@@A) C:Us...tions.obj Win32Project1

和:

Error 40 error LNK2005: "class std::vector<struct IndexVertexKey,class std::allocator<struct IndexVertexKey> > Geometry" (?Geometry@@3V?$vector@UIndexVertexKey@@V?$allocator@UIndexVertexKey@@@std@@@std@@A) already defined in D3DPipeline.obj C:Use...nagement.obj Win32Project1

(请注意,此处的编译错误与上面给出的示例没有直接关系,而是由它们引起的。

总而言之,我如何控制松散耦合的继承类(对象到对象)或我可以安全地引用包含而不会死亡交叉引用?

第一个错误是无定义错误。您需要在实现文件中定义静态成员变量(即 Direct3D.cpp ),

ID3D11Device* Direct3D::Device = nullptr; // or other initial value
第二个错误是重复的定义错误,

您应该将全局变量的定义放在实现文件中,而不是头文件中,因为头文件可能会多次包含并导致重复定义错误。