gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:47:47 24 4
gpt4 key购买 nike

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

我写了这个小程序:

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!5First!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!5First!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/

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