【问题标题】:How to properly expose C++ API using interfaces including derived interfaces?如何使用包括派生接口在内的接口正确公开 C++ API?
【发布时间】:2013-02-26 10:02:24
【问题描述】:

下面的代码说明了这个问题。我正在尝试为仅使用接口(C++ 虚拟类)的 C++ 组件创建 API。我有一个 Base 和 Derived 类,并且有相应的 IBase 和 IDerived 接口,但是当我尝试将 IBase 强制转换为 Derived 时,这会导致错误。 错误 C2594: 'type cast' : 从 'IBase *' 到 'Derived *' 的模糊转换

这似乎是我正在尝试做的一件合理的事情,Java 或 C# 不会对此嗤之以鼻。有没有办法在 C++ 中实现这样的目标

class IBase
{
public :
  virtual int method_A(void) = 0;
  virtual int method_B(void) = 0;
  virtual int method_C(void) = 0;
};

class IDerived : public IBase
{
public :
  virtual int method_D(void) = 0;
};

class Base : public IBase
{
  int method_A(void) {return 1;};
  int method_B(void) {return 2;};
  int method_C(void) {return 3;};
};

class Derived : public IDerived, private Base
{
public:
  int method_D(void) {return 4;};
};

class HandleDerived
{
public :
  int handle_base(IBase * i_base)
  {
    Derived * derived = (Derived *) i_base;
    return derived->method_D();
  }
};

【问题讨论】:

  • 使用虚拟继承
  • ...并且不要使用 C 风格的演员表。 ;-)

标签: c++ interface casting


【解决方案1】:

您正在查看的是多重继承。您的Derived 来自:

  • IDerived,派生自IBase
  • Base也是IBase派生的

因此,当您想在函数handle_base() 中处理IBase 指针(如Derived 指针)时,不清楚您指的是哪个IBase:来自IDerived 的那个,或者一位来自Base

解决方案可能是使用public virtual 继承。不过,您可能应该查看C++ FQA Light 关于此事的信息。

您关于“Java 或 C# 不会大惊小怪”的评论并不完全正确。即使是 C++ 中的纯虚拟基类仍然是一个,而不是一个接口(在 Java 的意义上),即你仍然有一个多重继承的情况。 Java的解决方案是区分类和接口; (其中之一)C++ 的解决方案是虚拟继承。

【讨论】:

    猜你喜欢
    • 2017-12-26
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    相关资源
    最近更新 更多