c++ - 我可以在 C++ 中覆盖非虚函数吗

标签 c++ overriding

我想知道我可以在 c++ 中覆盖非虚函数,因为我在玩 c++ 时发现了这个问题
覆盖 关键字我有如下代码

class A
{
public:
    void say()
    {
        cout << "From A\n";
    }
};
class B : public A {
public:
    void say()
        override
    {
        cout << "From B\n";
    }
};
但是当我执行代码时,visual studio 显示以下错误
'B::say':带有覆盖说明符 'override' 的方法没有覆盖任何基类方法
但是当我在 A 类中使用 virtual 关键字时,错误消失了,代码运行完美

最佳答案

你不覆盖在 B 中说
from C++ override specifier :

In a member function declaration or definition, override ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true.


看看那个例子:
#include <iostream>

class A
{
  public:
    void say()
    {
        std::cout << "From A\n";
    }
};

class B : public A {
  public:
    void say()
        //override
    {
        std::cout << "From B\n";
    }
};

int main()
{
  A a;
  B b;
  
  a.say();
  b.say();
  ((A &) b).say();
}
编译和执行:
pi@raspberrypi:/tmp $ g++ c.cc
pi@raspberrypi:/tmp $ ./a.out
From A
From B
From A
pi@raspberrypi:/tmp $ 
在 A 中说虚拟(在 B 中如此隐含)((A &) b).say();版画 From B因为那个时候有压倒一切的

关于c++ - 我可以在 C++ 中覆盖非虚函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62622047/

相关文章:

c++ - 在无向图中找到一个环(boost)并返回它的顶点和边

c++ - 不确定如何修复 "Member reference"错误

C++ 创建一个函数来获取两点之间的距离

c++ - 如何在cocos2d-x 2.2中检测三个 Sprite 的碰撞?

c++ - 提升图形库 : Is there a neat algorithm built into BGL for community detection?

java - 在给定实例上重写compareTo方法的更简单方法

java - toString() 不适用于父类(super class)和子类

java - 为什么不能在编译时覆盖而重载可以?

objective-c - 如果我重写派生类中的方法,是否应该在派生类的 header 中再次声明它?

c# - 使用反射确定 C# 方法是否具有关键字 'override'