c++ - 重新分配指针如何影响多态性
问题描述
这是我想知道的事情。有 2 个指针对应 2 个类实例。该代码打印出 6 行(根据注释)。前 4 行对我来说是有意义的,但我不明白后 2 行。我希望第 5 行和第 6 行等于第 3 行和第 4 行,因为pb
anpd
现在都指向同一个对象。请帮我理解。
#include <iostream>
using namespace std;
class B {
public:
virtual void run1(){cout << "Base" << endl;}
void run2(){cout << "Base" << endl;}
};
class D: public B {
public:
virtual void run1(){cout << "Derived" << endl;}
void run2(){cout << "Derived" << endl;}
};
int main(int argc, char* argv[])
{
B b, *pb;
D d, *pd;
pb = &b;
pb->run1(); //Base
pb->run2(); //Base
pd = &d;
pd->run1(); //Derived
pd->run2(); //Derived
pb = &d;
pb->run1(); //Derived (why ?)
pb->run2(); //Base (why ?)
}
解决方案
函数run1
是虚函数,而函数run2
不是虚函数。
虚函数根据使用指针的动态类型调用,非虚函数根据使用指针的静态类型调用。
指针的静态类型pb
是B *
.
B b, *pb;
在这个任务之后
pb = &b;
指针的动态类型也是B *
. 所以类中定义的虚函数B
被调用。
在这个任务之后
pb = &d;
指针的动态类型pb
从B *
变为 D *
。
所以在这个声明中
pb->run1(); //Derived (why ?)
根据指针的动态类型称为虚函数。虽然在此声明中
pb->run2(); //Base (why ?)
根据指针的静态类型称为非虚函数。
即在使用的指针指向的对象中搜索指向虚函数指针表的指针。
此功能定义了多态行为。
推荐阅读
- node.js - 错误:找不到模块,用于 controller.js 中的第三方库
- java - 所以我是编程新手我如何使性别 M 和 F 使它们小写和大写
- php - 使 2 个字段的组合唯一并在 laravel 中验证它们
- javascript - 如何在输入文本框中显示选定的值
- python - 字符串列表列表到字典列表
- android - Android Theme 样式不适用于 Button
- python - 如何从 HTML 标记中删除评论
- python - 使用 Python 在 Selenium 中转换测试函数
- c - 为什么我们需要一个单独的结构来保存 32 位 IPv4 地址
- node.js - 使用 bcrypt 和 jwt 的身份验证不起作用