Possible Duplicate:
Why does C++ not let baseclasses implement a derived class' inherited interface?
#include <iostream>
class Interface
{
public:
virtual void yell(void) = 0;
};
class Implementation
{
public:
void yell(void)
{
std::cout << "hello world!" << std::endl;
}
};
class Test: private Implementation, public Interface
{
public:
using Implementation::yell;
};
int main (void)
{
Test t;
t.yell();
}
我想要Test
要实现的类 Implementation
,我想避免需要编写
void Test::yell(void) { Implementation::yell(); }
方法。为什么不能这样做呢? C++03还有其他方法吗?
最佳答案
using
仅将名称带入范围。
它没有实现任何东西。
如果您想要像 Java 一样通过继承获取实现,那么您必须显式添加与之相关的开销,即虚拟
继承,如下所示:
#include <iostream>
class Interface
{
public:
virtual void yell() = 0;
};
class Implementation
: public virtual Interface
{
public:
void yell()
{
std::cout << "hello world!" << std::endl;
}
};
class Test: private Implementation, public virtual Interface
{
public:
using Implementation::yell;
};
int main ()
{
Test t;
t.yell();
}
编辑:这个功能有点偷偷摸摸,我必须编辑才能使用 g++ 编译代码。它不会自动识别实现
yell
和接口(interface) yell
是同一个。我不完全确定标准对此有何规定!
关于c++ - 为什么不能用 'using' 指令实现继承的纯虚方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12895892/