c++ - 我如何声明指向共享公共(public)接口(interface)的不同类的指针?

标签 c++ class interface

我正在使用一些这样定义的第 3 方库类。

class A : public Interface1, public Interface2 {};
class B : public Interface1, public Interface2 {};

它们不只共享一个公共(public)基类。是否可以声明一个可以同时引用 A 类和 B 类类型的指针类型?

请注意,我使用的是第三方库,无法重新定义 A 和 B。如果可以,我会这样做:

class Base : public Interface1, public Interface2 {};
class A : public Base {};
class B : public Base {};

然后我可以简单地使用一个指向 Base 类的指针。

Base *pBase;

最佳答案

如果不能重构代码,就不能直接这样做。

也就是说,您仍然可以创建一个删除类型的类,并且可以在需要指向 Interface1Interface2 的指针时使用。
例如:

struct S {
    template<typename T>
    S(T *t): iface1{t}, iface2{t} {}

    operator Interface1 *() { return iface1; }
    operator Interface2 *() { return iface2; }

private:
    Interface1 *iface1;
    Interface2 *iface2;
};

它有一个主要缺点,我不知道你是否可以处理:指向 S 的指针不能分配给指向 InterfaceN 的指针。
换句话说:

struct Interface1 {};
struct Interface2 {};

class A : public Interface1, public Interface2 {};
class B : public Interface1, public Interface2 {};

struct S {
    template<typename T>
    S(T *t): iface1{t}, iface2{t} {}

    operator Interface1 *() { return iface1; }
    operator Interface2 *() { return iface2; }

private:
    Interface1 *iface1;
    Interface2 *iface2;
};

int main() {
    A a;
    S sa{&a};

    // S can be assigned to a pointer to InterfaceN
    Interface1 *i1ptr = sa;
    Interface2 *i2ptr = sa;

    S *sptr = &sa;

    // sptr cannot be assigned to a pointer
    // to InterfaceN but you can get one
    // out of it dereferencing
    i1ptr = *sptr;
    i2ptr = *sptr;
}

如果你能接受,这是一个肮脏但可行的解决方法。


老实说,我不明白你为什么要那样做。您可以简单地创建函数模板并将指针传递给 AB 和所有其他类型。
无论如何,我不知道真正的问题是什么,我无法从问题中弄清楚。
因此,我希望它有所帮助。

关于c++ - 我如何声明指向共享公共(public)接口(interface)的不同类的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057379/

相关文章:

c# - 如何创建返回实现接口(interface)的类的类型的方法的通用接口(interface)?

c# - 理解反射

c# - 如何在运行时确定接口(interface)成员是否已实现?

c++ - 创建一个包含目录中文件名的 C++ 容器

c++ - 编译时指针 "does not have a type"?

c++ - 在模板参数中使用静态 constexpr 成员数组作为指针

python - 如何使用 Python 将字符串转换为类子属性

C++ Qt - QString remove() {brackets} 之间的正则表达式

c# - c# - 如何让一个类对象存储另一个类对象?

java - 多个类: What am I doing wrong here?