是否可以在 c++ 中为类分配未知结构?也许是虚拟函数之类的东西?还是将指针分配给结构?结构将在施工时分配,然后永远不会改变。
class Class{
void someFunction(){
//do something with the struct
};
struct unknownStruct;
};
struct Struct1{
int value1;
} struct1;
struct Struct2{
int value2;
int value3;
} struct2;
int main()
{
Class object1;
Class object2;
object1.struct=struct1;
object2.struct=struct2;
return 0;
}
您可以使用模板
template<class StructType>
struct Class {
void SomeFunction() { ... }
StructType myStruct;
};
或变体(如果结构数量有限(
struct S1 { };
struct S2 { };
struct Class {
void SomeFunction() { ... }
std::variant<S1, S2> myStruct;
};
或多态性
struct Base { virtual ~Base() = default; };
struct Class {
void SomeFunction() { ... }
std::unique_ptr<Base> myStruct;
};
或简单的空指针
struct Class {
void SomeFunction() { ... }
void* myStruct; //std::shared_ptr<void> might be safer to use
//or maybe std::any.
};