从外部访问静态成员并通过继承 c++ 访问静态成员
Accessing static member externally and through inheritance c++
我有一个类,其中包含一个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
第二个错误是重复的定义错误,您应该将全局变量的定义放在实现文件中,而不是头文件中,因为头文件可能会多次包含并导致重复定义错误。
- 如何在复杂继承中访问静态成员变量
- 如何在类内部使用和访问静态指针到成员值s_ptm?
- decltype:使用指针访问类的静态成员
- 是否通过单元化指针UB访问静态类成员
- 将对象数限制为1可以使用点运算符访问静态成员的1
- 多态性:通过类文本或对象访问静态成员
- 从另一个类访问静态成员函数
- 无法访问静态成员函数C++
- 从外部访问静态成员并通过继承 c++ 访问静态成员
- 通过非静态方法访问静态成员
- 如何在没有对象的情况下访问静态成员 (C++)
- 为什么链接器在内联构造函数中访问静态成员时失败
- 我可以在没有任何前向声明的类/结构上访问静态成员函数吗?
- 访问静态成员函数中的非静态成员的解决方法
- Visual C++ 使用成员选择运算符(. 或 –>)访问静态成员函数
- 使用boost::shared_ptr访问静态成员变量
- 非静态成员函数是否可以访问静态成员函数或数据
- 在c++中显式访问静态成员方法中的静态成员变量
- 无法访问静态成员 ->未解析的外部符号 i
- 通过运算符 [] 访问静态成员unordered_map