我可以用纯虚函数覆盖虚函数吗?

Can I override a virtual function with a pure virtual one?

我有三个 类:BDGDBGDBD 都是抽象的。 B 来自第三方。

B 有一个 G 需要实现的非纯虚方法(成为 D)。我可以 redefine/override 一个虚函数是纯虚的吗?

示例:

class B // from a third party
{
public:
   virtual void foo();
};

class D : public B
{
public:
   void foo() override = 0; // allowed by gcc 4.8.2
   virtual void bar() = 0;
};

class G : public D
{
public:
   // forgot to reimplement foo
   void bar() override;
};

int main()
{
   G test;  // compiler error is desired
}

关于 "can I?" 的问题,gcc 允许它,但我没有 terms/vocabulary 来验证该行为是标准的一部分还是未定义并且今天碰巧有效。

如果您使用更现代的编译器编译代码,您将收到以下解释问题的错误消息

prog.cc:23:6: error: variable type 'G' is an abstract class
   G test;  // compiler error is desired
     ^
prog.cc:10:9: note: unimplemented pure virtual method 'foo' in 'G'
   void foo() override = 0; // allowed by gcc 4.8.2
        ^
1 error generated.

至于标准(10.3虚函数)

11 A virtual function declared in a class shall be defined, or declared pure (10.4) in that class, or both; but no diagnostic is required (3.2).

您问的是:

Can I override a virtual function with a pure virtual one?

答案是:可以。来自 C++11 标准:

10.4 Abstract classes

5 [ Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure. —end note ]