从外部访问静态成员并通过继承C++
Accessing static member externally and through inheritance c++
我有一个 class,里面有一个 ID3D11Device
成员,我想将其设为 static
,因为现在,我希望可以访问 ID3D11Device
通过多个 Entity
class 个实例。问题是,如果不直接实例化 Direct3D
class,我无法访问 Direct3D
class,将 ID3D11Device
静态成员置于其对象之外。
因为多个 classes 继承自 Direct3D
class(对于 hwnd
细节又继承自 WindowsClass
),我会喜欢将其作为基础 class,以保持对继承自 Direct3D
的所有 class 的访问权限,如本示例所建议的:
class Direct3D: WindowsClass{
public:
Direct3D();
~Direct3D();
static ID3D11Device* Device;
}
还有继承的class:
class EntityType: Direct3D{
public:
EntityType();
~EntityType();
void SomeDeviceDependentFunction();
}
成员定义为:
void EntityType::SomeDeviceDependentFunction(){
//Perform some action calling Direct3D::Device.
}
注意class 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
(请注意,此处的编译错误与上面给出的示例没有直接关系,而是由它们引起的。)
总而言之,我如何控制继承的 class 松散耦合(对象到对象)或者我可以安全地引用包含而不会死于交叉引用的地方?
第一个错误是无定义错误。您需要在实现文件中定义静态成员变量(即Direct3D.cpp
),
ID3D11Device* Direct3D::Device = nullptr; // or other initial value
第2个错误是重复定义错误,应该将全局变量的定义放在实现文件中,而不是头文件中,这样可能会多次包含导致重复定义错误
我有一个 class,里面有一个 ID3D11Device
成员,我想将其设为 static
,因为现在,我希望可以访问 ID3D11Device
通过多个 Entity
class 个实例。问题是,如果不直接实例化 Direct3D
class,我无法访问 Direct3D
class,将 ID3D11Device
静态成员置于其对象之外。
因为多个 classes 继承自 Direct3D
class(对于 hwnd
细节又继承自 WindowsClass
),我会喜欢将其作为基础 class,以保持对继承自 Direct3D
的所有 class 的访问权限,如本示例所建议的:
class Direct3D: WindowsClass{
public:
Direct3D();
~Direct3D();
static ID3D11Device* Device;
}
还有继承的class:
class EntityType: Direct3D{
public:
EntityType();
~EntityType();
void SomeDeviceDependentFunction();
}
成员定义为:
void EntityType::SomeDeviceDependentFunction(){
//Perform some action calling Direct3D::Device.
}
注意class 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
(请注意,此处的编译错误与上面给出的示例没有直接关系,而是由它们引起的。)
总而言之,我如何控制继承的 class 松散耦合(对象到对象)或者我可以安全地引用包含而不会死于交叉引用的地方?
第一个错误是无定义错误。您需要在实现文件中定义静态成员变量(即Direct3D.cpp
),
ID3D11Device* Direct3D::Device = nullptr; // or other initial value
第2个错误是重复定义错误,应该将全局变量的定义放在实现文件中,而不是头文件中,这样可能会多次包含导致重复定义错误