C++为API中定义的结构创建超类
C++ Create superclass for structs defined in API
我有一个API接口,无法更改。接口包含两个结构。由于它们非常相似,我希望将两个结构的实例存储在同一个集合中。
据我所知,我需要为这些结构创建一个超类,这样我就可以将这两个结构的实例添加到集合中。但是,在不改变界面本身的情况下,有可能做到这一点吗?
您不能在c++中创建类的超类,但您可以使用std::variant将两个结构添加到集合中。
或者,如果每个结构中都有特定的变量/方法,您希望以相同的方式访问它们,则可以创建一个新的类来封装这两个结构:
// structs from the API
struct A {
int some_int;
string some_string;
};
struct B {
int some_int;
string some_string;
}
// new struct that you write
struct ABInterface {
int some_int;
string some_string;
// "copy" constructor from A object
ABInterface(A a) {
some_int = a.some_int;
some_string = a.some_string;
}
// "copy" constructor from B object
ABInterface(B b) {
some_int = b.some_int;
some_string = b.some_string;
}
}
相关文章:
- 如何在C++类内存结构中创建"spacer"?
- 创建结构的数组时遇到分段错误
- 如何在 c++ 中创建结构向量的映射
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- C++为API中定义的结构创建超类
- C++ 使用数组结构创建平衡的二叉搜索树
- 使用匿名联合为结构创建空构造函数
- 正确的结构创建
- OPENDDS-从单个IDL结构创建多个主题
- 是否可以使用给定参数为结构创建推力的功能谓词?
- MFC文档/视图体系结构-创建没有初始视图的文档
- 在c++结构创建中更快地执行
- JNA -结构创建错误
- C++中模板结构创建之间的差异
- 无法推送到由静态映射<结构创建的队列,队列>
- 为类/结构创建多个对象
- 如何从模板结构创建二维数组
- 指向从另一个结构创建的数组的指针(不确定措辞是否正确)C++
- 使用结构创建数组