【问题标题】:Overriding a virtual function but not a pure virtual function?覆盖虚函数而不是纯虚函数?
【发布时间】:2022-01-13 22:50:31
【问题描述】:

我正在尝试从 AB 这两个类派生一个类 C;在阅读了this answer 之后,我尝试编写using B::<function>,以便用B 中的实现覆盖A 中的纯虚函数。

但是,该答案中的方法不适用于 pure 虚函数;在那种情况下,我发现我需要更加明确。 所以显然using 可以解决歧义,但它不能引入实现? 我只是希望能更好地了解这里发生了什么。

struct A {

    // this would result in ambiguity:
    //virtual void e(void) const {}   // ERROR: member 'e' found in multiple base classes 

    // resolving ambiguity with 'using'
    virtual void f(void) const {}     // OK

    // this would result in an unimplemented method:
    //virtual void g(void) const = 0; // ERROR: variable type 'C' is an abstract class

    // *** why doesn't this work? ***
    //virtual void h(void) const = 0; // ERROR: variable type 'C' is an abstract class

    // resolving ambiguity by explicitly defining what I want
    virtual void i(void) const = 0;   // OK
};
struct B {    
    void e(void) const {}
    void f(void) const {}
    void g(void) const {}
    void h(void) const {}
    void i(void) const {}
};
struct C : public A, public B {
    using B::f;                    // sufficient to pin down 'f'
    using B::h;                    // not sufficient to pin down 'h'
    void i(void) const { B::i(); } // sufficient to pin down 'i'
};
int main() {
    C X;
    X.e();
    X.f();
    X.g();
    X.h();
    X.i();
}

【问题讨论】:

  • not enough to pin down 'h'“pin down”是什么意思?
  • 我不确定问题是什么。您的示例似乎工作得很好,并且可以按照您的期望进行。 ideone.com/RqXpFe

标签: c++ abstract-class multiple-inheritance using virtual-functions


【解决方案1】:

我尝试使用B::<function> 来覆盖纯 A 中的虚函数与 B 中的实现。

你误会了。以这种方式覆盖 一个函数是不可能的。 using B::h; 所做的一切:它将B::h 引入struct C 的范围,因此main() 中的X.h(); 等效于X.B::h();。因此,A::h() 仍然是纯虚拟的,因此您无法实例化 struct C

【讨论】:

    猜你喜欢
    • 2013-10-04
    • 2021-09-30
    • 2020-08-21
    • 2014-05-22
    • 2021-11-01
    • 2013-01-16
    • 2016-02-05
    • 2011-02-24
    • 1970-01-01
    相关资源
    最近更新 更多