调用重写的虚函数而不是重载

调用重写的虚函数而不是重载

本文介绍了调用重写的虚函数而不是重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这部分代码:

#include<iostream>
using namespace std;
class A {
public:
    virtual int f(const A& other) const { return 1; }
};
class B : public A {
public:
    int f(const A& other) const { return 2; }
    virtual int f(const B& other) const { return 3; }
};

void go(const A& a, const A& a1, const B& b) {
    cout << a1.f(a) << endl; //Prints 2
    cout << a1.f(a1) << endl; //Prints 2
    cout << a1.f(b) << endl; //Prints 2
}
int main() {
    go(A(), B(), B());
    system("pause");
    return 0;
}

我能理解为什么前两个会打印2.但是我不明白为什么最后一个也会打印2.为什么它不喜欢B中的重载函数?

I can understand why the first two will print 2. But I cannot understand why the last print is also 2. Why doesn't it prefers the overloaded function in B?

我已经查看了和,但我无法从中理解.

I already looked at this and this but I couldn't manage to understand from these.

推荐答案

int B::f(const B& other) const不会覆盖 int A::f(const A& other) const,因为参数类型不同.这样就不会通过引用基类A调用f()来调用它.

int B::f(const B& other) const doesn't override int A::f(const A& other) const because the parameter type is not the same. Then it won't be called via calling f() on reference of the base class A.

name
parameter type list (but not the return type)
cv-qualifiers
ref-qualifiers

然后,派生类中的此函数也是虚拟的(无论是 声明中没有使用关键字virtual)和 overrides Base :: vf(是否在其单词中使用override一词 声明).

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).

如果使用覆盖说明符(自C ++ 11起),编译器将产生错误.

If you use override specifier (since C++11) compiler will generate the error.

class B : public A {
public:
    int f(const A& other) const { return 2; }
    virtual int f(const B& other) const override { return 3; }
};

例如 C语:

source_file.cpp:10:17: error: 'f' marked 'override' but does not override any member functions
    virtual int f(const B& other) const override { return 3; }
                ^

如果在基类中为其添加重载,则可能会得到所需的内容.请注意,将需要类B的前向声明.

If you add an overload for it in the base class, you might get what you want. Note that a forward declaration of class B will be needed.

class B;
class A {
public:
    virtual int f(const A& other) const { return 1; }
    virtual int f(const B& other) const { return 1; }
};

这篇关于调用重写的虚函数而不是重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 20:02