c++ - 为什么不能用 'using' 指令实现继承的纯虚方法?

标签 c++ interface using-directives

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/

相关文章:

android - 分类器没有伴随对象,因此必须在这里初始化

c# - 命名空间和使用指令

c++ - 使用 auto&& 完美转发返回值

c++ - 从模板派生类调用模板基类的构造函数

c++ - 当派生类添加了数据成员时,派生类的构造函数应该如何在 C++ 中使用

android - Kotlin - 接口(interface)中的只读属性

c++ - 虚拟机上的Visual Studio 2013 C++链接静态库glew、glfw

java - 静态 final 列表的接口(interface)或类?

c++ - 详细命名空间中的 using 指令是否有问题?

c++ - 为什么经验丰富的编码人员使用 std::而不是使用命名空间 std;?