源自C ++类和接口 [英] Deriving from a C++ class and an interface

查看:83
本文介绍了源自C ++类和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在尝试开发一个基类和一个派生类.每个继承一个接口(一个基本接口和一个派生接口).

I am trying to develop a base class and a derived one. Each one inheriting an interface (a base interface and a derived interface).

在下面的代码中,tt不太清楚为什么 MethodOfBase()方法必须在派生类中重新实现 CDerived ?如果不是,则编译器会对此抱怨.我当时以为 从 CBase 中获得 CDerived ,它将解决这个问题.

In my code below, tt is not very clear why the MethodOfBase() method has to be re-implemented in the derived class CDerived below? If not, then the compiler complains about it. I was thinking that by deriving CDerived from CBase, this will take care of it.

还可以使用一种更优雅的编码方式吗?


// IBase
interface IBase
{
public:
	virtual HRESULT STDMETHODCALLTYPE MethodOfBase() = 0;
};

// IDerived
interface IDerived : public IBase
{
public:
	virtual HRESULT STDMETHODCALLTYPE MethodOfDerived() = 0;
};

// CBase
class CBase : public IBase
{
public:
	STDMETHODIMP MethodOfBase() { return S_OK; }
};

// CDerived
class CDerived : public IDerived,
				 public CBase
{
public:
	STDMETHODIMP MethodOfBase()  { return CBase::MethodOfBase() ; }	// Why is this required?
	STDMETHODIMP MethodOfDerived() { return S_OK; }
};

// main
int main()
{
	CDerived obj;
	return 0;
}

推荐答案

我个人是C ++多重继承的忠实拥护者(与C#单一继承和接口实现相比).但是,您遇到了我个人不惜一切代价避免出现的一种情况-涉及多重继承相同的情况 基类.

I am personally a big fan of C++ Multiple Inheritance (compared to C# single inheritance and interface implementation).  However you have hit on the one scenario that I personally try to avoid at all costs -- which involves multiply inheriting the same base class.

 

IBase
 |
 |
IDerived      IBase
 \             /
  \            /
   \          /
    \         /
    CBase    IDerived 
      \       /
       \     /
        \   /
      CDerrived

查看您的继承图(MS代码格式化程序使用比例字体的歉意)

 

Look at your inheritance diagram (Apologies that the MS code formatter uses a proportional font)

 

您有两个IBase副本,这意味着您必须两次实施MethodOfBase.您可以通过CBase获得一个实现,但是其他分支中没有实现.

You have two copies of IBase, which implies that you have to implement MethodOfBase twice.  You get one implementation via CBase, but you have no implementation in your other branch.

您可以在IDerived中使用虚拟继承来合并树的分支,但这会带来全新的蠕虫病毒. (与MI有关的问题是仅使用Java和C#的SI之间的很大动机).在您选择任何一条路线之前,我强烈建议 您会仔细阅读有关MI的问题,以及在继承层次结构中多次使用同一个基类的含义.我个人强烈建议您完全避免使用它,并且仅将MI仅用于不同的对象层次结构.

You could use virtual inheritance in IDerived to merge the branches of your tree, but that brings in a whole new can of worms. (This issue with MI is a large motivation between the SI only in Java and C#).  Before you go either route, I strongly suggest you look read up on the issues with MI and what it means to use the same base class more than once in an inheritance heiarchy.  I personally strongly suggest you avoid it altogether and only use MI only for distinct hierarchies of objects.


这篇关于源自C ++类和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆