【发布时间】:2009-04-30 12:02:14
【问题描述】:
我想在 c++ 中使用接口,例如在 java 或 c# 中。我决定使用具有多重继承的纯抽象类,但是当我专门化接口时出现了严重错误:
class Interface
{
public:
virtual int method() = 0;
};
// Default implementation.
class Base: virtual public Interface
{
public:
virtual int method() {return 27;}
};
// specialized interface
class Interface2: public Interface
{
public:
virtual int method() = 0;
// some other methods here
};
// concrete class - not specialised - OK
class Class: public virtual Interface, public virtual Base
{
};
// concrete class - specialised
class Class2: public Interface2, public Base
{
};
int main()
{
Class c;
Class2 c2;
return 0;
}
警告 1 警告 C4250: 'Class' : 通过支配 30 继承 'Base::Base::method'
错误 2 错误 C2259: 'Class2' : 无法实例化抽象类 42
这样做的正确方法是什么?
【问题讨论】:
-
为什么不对 Class2 使用虚拟继承?
-
另一个问题是您为什么要尝试用 C++ 重新实现 Java?
-
你到底想做什么?你想要mixins,一个基类中的方法可以调用另一个基类中的方法,还是只是“常规”多重继承?如果是后者,为什么要使用虚拟继承,为什么要同时继承Interface和Base(后者就足够了)?
-
要明确:请准确描述您对 Class 和 Class2 的期望行为(例如,调用 method() 时应该发生什么;可以使用对 Interface2 的指针/引用来指向实例) .
-
如果方法没有在 Class2 或 Class 中重新实现(在这种情况下不是) Base::method() 将被调用。否则将调用重新实现。有一个具有通用基础哑实现的接口层次结构。
标签: c++