gpt4 book ai didi

c++ - 调用覆盖的虚函数而不是重载

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:09 24 4
gpt4 key购买 nike

假设我有这部分代码:

#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 中的重载函数?

我已经看过 thisthis但我无法从中理解。

最佳答案

int B::f(const B& other) const 不是 override int A::f(const A& other) const 因为参数类型不一样。然后它不会通过调用基类 A 的引用上的 f() 来调用。

If some member function vf is declared as virtual in a class Base, and some class Derived, which is derived, directly or indirectly, from Base, has a declaration for member function with the same

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

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).

如果您使用 override specifier (C++11 起)编译器会产生错误。

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

Clang :

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 的前向声明。

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

LIVE

关于c++ - 调用覆盖的虚函数而不是重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38096552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com