c++ - vptr调用虚函数
问题描述
我最近在阅读有关 C++ 中的虚函数和继承的内容,最后读到了 vptr 和 VTABLE。
我的问题与使用 vprt 调用派生对象的方法有关。
我解释一下,下面是我的代码:
#include <iostream>
using namespace std;
class base
{
public:
void fun_1() { cout << "base-1\n"; }
virtual void fun_2() { cout << "base-2\n"; }
virtual void fun_3() { cout << "base-3\n"; }
virtual void fun_4() { cout << "base-4\n"; }
};
class derived : public base
{
public:
void fun_1() { cout << "derived-1\n"; }
void fun_2() { cout << "derived-2\n"; }
void fun_4() { cout << "derived-4\n"; }
};
int main()
{
base *p;
derived obj1;
p = &obj1;
void(*firstfunc)() = (void(*)(void))(*(int*)*(int*)p);
firstfunc();
}
结果是:
衍生-2
好的,到目前为止,(void(*)(void))(*(int*)*(int*)p)
我的脑海中仍然模糊不清,我该怎么做才能调用第二个函数?
谢谢
解决方案
how could I do to call the second function ?
You would call it like this:
p->fun_2();
prints:
derived-2
Virtual tables and virtual function pointers are implementation details of your compiler. In general you should not care about such implementation details, because if you do you write non-portable code. Actually I am not even sure if your code has undefined behaviour or not, if it does then even a compiler that does place the vpointer at the place you expect could print garbage. Anyhow, dont do it, unless you need to, which is actually never ;).
As a sidenote, function pointers loose lots of their scariness if you use aliases, eg
using base_mem_fun = void (base::*)();
base_mem_fun first_base = &base::fun_1;
(p->*first_base)();
prints:
base-1
推荐阅读
- python - Alexa 技能 Python Flask ask 和 SocketIO with Unity
- java-8 - 在 ubuntu 上安装 jdk8 时出错
- python-3.x - 如何使小部件适合整个框架以在 tkinter 中调整大小?
- scala - Spark Scala withColumn getItem
- docker - Hyperledger Fabric:定义 docker-compose 时要使用的 MSP 目录
- java - 根据 queryurl 中存在的键,将字符串替换为完全匹配的单词
- ios - 获取距离 eddystone 信标
- java - 计算两个纬度、经度点之间的持续时间或预期行驶时间
- android - 回收站视图项目不滚动?
- powershell - 如何使用 powershell 更改文件内容并将其保存到另一个文件?