为什么无法使用'using'指令实现继承的纯虚拟方法?
why it is not possible to implement inherited pure virtual method with 'using' directive?
可能的重复:
为什么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
是同一个。我不完全确定标准是怎么说的!相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 为什么我可以通过SubBase类的公共继承方法打印出基类的私人继承成员
- C++ 实例化新对象时不接受继承方法默认参数值
- 从基类(车辆)继承方法,从派生类(汽车)继承值,以使用 C++ 在另一个派生类(车道)中实现
- 将方法添加到与继承方法相同的子类
- 重写2个重载的继承方法c++中的一个
- 从抽象类继承方法
- C++调用模板化超类的继承方法
- 继承方法,派生方法调用的不是基
- C++派生类继承方法错误
- 调用模板函数内部的继承方法
- 企业架构师 - 从类图中的接口继承方法
- 调用继承方法-编译器错误
- 计算继承方法时出错
- 调用继承方法
- 派生类的继承方法不起作用
- 在c++中推导继承方法的父类
- Qt QTableView多重继承方法
- 主类无法从我的第二个类继承方法
- c++多重继承方法重载