为什么无法使用'using'指令实现继承的纯虚拟方法?

why it is not possible to implement inherited pure virtual method with 'using' directive?

本文关键字:继承 方法 虚拟 实现 using 为什么 指令      更新时间:2023-10-16

可能的重复:
为什么C++不让基类实现派生类';继承的接口?

#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的get,那么你必须显式地添加与之相关的开销,即virtual继承,如下所示:

#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();
}


EDIT:这个功能有点狡猾,我不得不进行编辑以使代码使用g++编译。它没有自动识别出实现yell和接口yell是同一个。我不完全确定标准是怎么说的!