c++ - 使用指令和抽象方法

标签 c++

我有一个类(我们称它为 A)继承了一个接口(interface),该接口(interface)定义了几个抽象方法,另一个类在那里考虑了一些代码(我们称它为 B)。

问题是,我在A实现的接口(interface)中有一个抽象方法只是为了调用B版本。有没有办法使用关键字 using 来避免编写像这样的沉闷方法:

int A::method() override
{
  return B::method();
}

我尝试使用 B::method 在 A 中编写,但我仍然收到 A 未从接口(interface)实现抽象方法的错误。 在这种情况下是否有特殊的技术可以使用,或者我只是运气不好? (如果是这样,是否有特定原因为什么应该这样?)。

谢谢。

编辑: 澄清一下,问题是,为什么不能只这样做:

class A: public Interface, public B {
  using B::method;
};

最佳答案

让我们弄清楚这一点。你基本上有以下问题,对吧?

struct Interface
{
    virtual void method() = 0;
};

struct B
{
    void method()
    {
        // implementation of Interface::method
    }
};

struct A : Interface, B
{
     // some magic here to automatically
     // override Interface::method and 
     // call B::method
};

这根本不可能,因为从技术角度来看,方法具有相同名称这一事实是无关紧要的。换句话说,Interface::methodB::method 根本没有关系,它们的相同名称不过是巧合,就像其他人一样叫“朱利安”与你没有任何关系,只是因为你们有相同的名字。

您基本上只剩下以下选项:

1.) 只需手动编写调用:

struct A : Interface, B
{
    virtual void method()
    {
        B::method();
    }
};

2.) 尽量减少使用宏编写的工作,这样您就可以编写:

struct A : Interface, B
{
    OVERRIDE(method)
};

但我强烈建议不要使用此解决方案。减少您的写作工作 = 增加其他人的阅读工作。

3.) 更改类层次结构,以便 B 实现 Interface:

struct Interface
{
    virtual void method() = 0;
};

struct B : Interface
{
    virtual void method()
    {
        // implementation of Interface::method
    }
};

struct A : B
{
};

关于c++ - 使用指令和抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24696549/

相关文章:

c++ - 测试使用协作者和模板化方法的类

c++ - 如何编写以对象为参数的可变参数模板函数?

c# - 使用 .NET Core 2.1 的托管 C++

c++ - 在 MatLab 中执行 CUDA mexfunction 期间尝试保存到 .txt 时出错

c++ - 程序运行周期中代码块Ver.16.01崩溃

C++ 和 python : TypeError resolution for vector arguments ? 。

c++ - 管道优化,这样做有什么意义吗?

c++ - 无法创建类实例

c++ - 嵌套在函数中的函数声明的命名空间

c++ - 如何有效地改变矩阵的连续部分?