c++使用指针取出虚函数
时间: 2024-01-13 08:02:31 浏览: 91
使用指针取出虚函数的过程如下:
```c++
//定义一个基类
class Base {
public:
virtual void func() {
cout << "This is Base class." << endl;
}
};
//定义一个派生类
class Derived : public Base {
public:
void func() {
cout << "This is Derived class." << endl;
}
};
int main() {
//定义一个指向派生类对象的指针
Derived* derived = new Derived();
//定义一个指向基类对象的指针,并将其指向派生类对象
Base* base = derived;
//使用指针调用虚函数
base->func();
//使用指针取出虚函数
void (*pFunc)() = (void (*)())(*(int*)*(int*)(&base));
//调用取出的虚函数
pFunc();
return 0;
}
```
输出结果为:
```
This is Derived class.
This is Derived class.
```
阅读全文