C++为API中定义的结构创建超类

C++ Create superclass for structs defined in API

本文关键字:结构 创建 超类 定义 API C++      更新时间:2023-10-16

我有一个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;
}
}