c++ - 实现具有多重继承的纯虚函数

标签 c++ inheritance multiple-inheritance pure-virtual

假设有这个接口(interface):

class A{  
 public:  
  virtual foo()=0;  
};

还有一个类 B 实现了这个接口(interface):

class B:public A{    
 public:   
  virtual foo(){} //Foo implemented by B   
}

最后,一个 C 类,它有 AB 作为基类:

Class C : public A, public B {
};

我的问题是,有一种方法可以告诉编译器 foo 的实现是来自类 B 的实现,而无需显式调用 B::foo()?

最佳答案

正如@BenVoigt 在评论中指出的那样,以下答案仅适用于 g++ 中的错误(这意味着它不能保证继续工作,而且绝对不可移植)。因此,尽管如果您使用特定的(有问题的)编译器它可能会执行您想要的操作,但它不是您应该使用的选项。

使用 virtual inheritance尽管。


这不完全是问题中的代码所暗示的场景,而是句子

My question is, there is a way to tell the compiler that the implementation for foo is the one from class B without doing an explicit call to B::foo()?

似乎要求语法在不使用 :: 限定符的情况下区分函数的多个基本版本。

您可以使用 using 指令执行此操作:

#include <iostream>
class A {
public:
A(){}
virtual void foo(){std::cout<<"A func";}
};

class B: virtual public A {
  public:
  B(){}
  virtual void foo(){std::cout<<"B func";}
};
class C:virtual public A, virtual public B {
    public:
    C(){}
    using A::foo; // tells the compiler which version to use
                   // could also say using B::foo, though this is unnecessary
};

int main() {
    C c;
    c.foo(); // prints "A func"
    return 0;
}

当然,正如其他答案所指出的,问题中的代码本身根本不需要这样做。

关于c++ - 实现具有多重继承的纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14044222/

相关文章:

java - 如何构造一个需要从构造函数传入值的方法?

c++ - 继承与聚合以及 "has-a"与 "is-a"。

c++ - 这个类的一个对象分配了多少内存?

java - 子类型 "inherit"通用接口(interface)是否使用该特定子类型 (Java) 进行参数化?

具有纯虚运算符+函数的 C++ 抽象基类

c# - .Net 泛型——从接口(interface)实现继承

C++ 函数调用标识符

c++ - 程序结构

c++ - 编译时构造函数选择

c++ - 在代码中解释继承?