c++ - 具有不同参数类型的虚函数

标签 c++ class inheritance virtual-functions

我试图了解虚函数的工作原理,但我卡在了某个部分。

我写了这个小程序:

class First
{
public:
    virtual void f(int a) 
    {
        cout << "First!" << endl;
        cout << a << endl;
    }
};

class Second : public First
{
public:
    void f(int a) {
        cout << "Second!" << endl;
        cout << a << endl;
    }
};

void main() {
    Second s;
    First *p = &s;
    p->f(5);
    First n;
    p = &n;
    p->f(3);
    _getch();
}

此代码导致:

Second!
5
First!
3

However, if I change int in the Second::f() function to a different type, like this:

class First
{
public:
    virtual void f(int a) {
        cout << "First!" << endl;
        cout << a << endl;
    }
};

class Second : public First
{
public:
    void f(double a) { //double instead int here!
        cout << "Second!" << endl;
        cout << a << endl;
    }
};

void main() {
    Second s;
    First *p = &s;
    p->f(5);
    First n;
    p = &n;
    p->f(3);
    _getch();
}

我的程序从不调用 Second::f(),结果是这样的:

First!
5
First!
3

有人可以向我解释为什么会这样吗?

最佳答案

当使用虚函数调度时,所谓的“最终覆盖器”就是被调用的。对于甚至覆盖继承的虚函数的函数,它必须满足一些条件:

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and refqualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

-- ISO/IEC 14882:2001(E) §10.3(粗体强调我的)

很简单,在您的第二个示例中,Second::f(double) 的参数列表与 First::f(int) 的参数列表不同,因此 Second::f(double)不是(自动)虚拟的并且不是覆盖First::f(int) .

C++11 关键字 override 声明了您的意图,即方法覆盖继承的虚拟方法,以便编译器可以在不覆盖时告诉您。例如,如果您改为这样做:

void f(double a) override {

编译器会给你这个诊断来告诉你它实际上并没有覆盖任何东西,它甚至会告诉你为什么它没有(“第一个参数类型不匹配('int' vs 'double ')"):

main.cpp:15:18: error: non-virtual member function marked 'override' hides virtual member function
void f(double a) override { //double instead int here!
                 ^
main.cpp:7:14: note: hidden overloaded virtual function 'First::f' declared here: type mismatch at 1st parameter ('int' vs 'double')
virtual void f(int a) {
             ^

关于c++ - 具有不同参数类型的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43644194/

相关文章:

java - 如何访问并打开 .class 文件

C++ - 在哪里编写继承对象的成员函数

python - 从对象内部获取分配给该对象的变量?

python:继承类中连续的 __getitem__() 调用?

java - 为两个扩展 super 的类制作比较器

c++ - 导出的函数名称不包含参数列表

c++ - 与MATLAB相比,OpenCV从视频文件中提取的帧更少

c++ - 局部常量变量不是 constexpr 可评估的,但无法弄清楚为什么

c++ - 关于我游戏中继承的一个问题

python - Python 中的多个参数类