虚拟继承和虚拟基类的转换

时间:2012-11-02 14:18:05

标签: c++ inheritance virtual

我遇到了有关虚拟继承的特定问题。 下面的代码解释了结构。

// Header

struct ITarget
{
    virtual void SetValue() = 0;
};

struct ISource
{
    virtual void GetValue() const = 0;
};

struct IBase
{
    virtual void Stuff() = 0;
};

struct IInput :
    virtual public IBase, public ITarget
{
    // Publicly acts only as Target
};

struct IOutput :
    virtual public IBase, public ISource
{
    // Publicly acts only as Source
};

// Implementation

struct SBase :
    virtual public IBase, virtual public ISource, virtual public ITarget
{
    // IBase
    virtual void Stuff();

    // ISource
    virtual void GetValue() const;

    // ITarget
    virtual void SetValue( );
};

struct SInput :
    public IInput, public SBase
{
    // Defines ITarget and ISource per SBase
};

struct SOutput :
    public IOutput, public SBase
{
    // Defines ITarget and ISource per SBase
};

int main()
{
  // To demonstrate the behavior
  ISource* input = new SInput();
  ((SInput*)input)->GetValue();
  return 0;
}

现在,如果我想将 ISource *转换为 SInput *,我会收到错误C2635:

  

"无法转换' ISource *'到一个SInput *&#39 ;;从虚拟转换   基类隐含在"

我究竟如何设置继承以实现这一目标?

0 个答案:

没有答案