gpt4 book ai didi

c++ - 涉及虚函数的C++代码的输出说明

转载 作者:太空宇宙 更新时间:2023-11-04 12:37:47 26 4
gpt4 key购买 nike

我想了解以下涉及虚函数的 C++ 程序的输出背后的原因。还请解释在以下2种情况下如何生成函数指针表和包含函数指针表链接的虚拟指针表,以及如何在运行时解析调用。

/******* PROGRAM 1 *******/
#include <iostream>
using namespace std;

class Car {
public:
virtual void foo() {
cout<<"Car"<<endl;
}
};

class Bmw: public Car {
public:
void foo1() {
cout<<"Bmw"<<endl;
}
};

int main() {
Car *c = new Bmw();

c->foo(); // gives output Car even though foo()
//function does not exist in BMS class.

return 0;
}

/******* PROGRAM 2 *******/
#include<iostream>
using namespace std;

class Car {
public:
virtual void foo() {
cout<<"Car"<<endl;
}
};

class Bmw: public Car {
public:
void foo() {
cout<<"Bmw"<<endl;
}
};

class Bmw7: public Bmw {
public:
void foo1(){
cout<<"Bmw7"<<endl;
}
};

int main() {
Car *c = new Bmw7();

c->foo(); //gives output Bmw. Why output is not Car ??
return 0;
}

最佳答案

Here是对虚函数和虚表的一个很好的解释。

Every class that uses virtual functions (or is derived from a class that uses virtual functions) is given its own virtual table

Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.

这几乎可以回答您的问题。在第一个示例中,c 可访问的最派生函数是Carfoo。在第二个中,它是 Bmwfoo。这里即使你没有在 Bmwfoo 前面写 virtual(这不是一个很好的编码风格),它的虚拟性是继承自 Car

编辑:正如评论中正确指出的那样,vtables 不是标准的一部分。参见 this reference以获得更正式的解释。

For every virtual function, there is the final overrider, which is executed when a virtual function call is made. A virtual member function vf of a base class Base is the final overrider unless the derived class declares or inherits (through multiple inheritance) another function that overrides vf.

关于c++ - 涉及虚函数的C++代码的输出说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55604650/

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