【发布时间】:2015-11-21 18:45:59
【问题描述】:
我知道有很多关于 MI 的问题,但是,似乎没有人回答我的问题。我有以下最小示例:
#include <iostream>
struct Base{
virtual void foo() = 0;
};
struct A : public virtual Base{
void foo(){
std::cout << "A::foo()" << std::endl;
}
void foo( int a){
std::cout << "A::foo(int a)" << std::endl;
}
};
struct B : public virtual Base{
virtual void foo( int a ) = 0;
};
struct C : public B,public A{
using A::foo;
};
int main( int argc, char* argv[]){
C c;
c.foo();
c.foo( 1 );
}
其中 Base 和 B 完全是虚拟类,A 提供所有实现。但是,代码没有编译,而是给了我以下错误消息
mh.cpp: In function ‘int main(int, char**)’:
mh.cpp:22:11: error: cannot declare variable ‘c’ to be of abstract type ‘C’
C c;
^
mh.cpp:17:12: note: because the following virtual functions are pure within ‘C’:
struct C : public B,public A{
^
mh.cpp:15:22: note: virtual void B::foo(int)
virtual void foo( int a ) = 0;
我想要的行为可以通过扩展类C来实现
struct C : public B,public A{
using A::foo;
void foo( int a ){
A::foo( a );
}
};
但是,我不希望添加这种多余的方法。有什么方法可以达到这个效果吗?
【问题讨论】:
-
你能把
virtual void foo( int a) = 0;加到Base吗? -
我建议在您认为覆盖虚函数的任何地方使用 C++11 中可用的新
override说明符。它使此类问题更容易找到。 -
非常感谢。我认为我可以像在 Java 中使用接口一样使用虚拟类。我意识到我不能也将相应地更新我的设计。
标签: c++ multiple-inheritance virtual-functions overriding virtual-inheritance