首页 > 解决方案 > 重新分配指针如何影响多态性

问题描述

这是我想知道的事情。有 2 个指针对应 2 个类实例。该代码打印出 6 行(根据注释)。前 4 行对我来说是有意义的,但我不明白后 2 行。我希望第 5 行和第 6 行等于第 3 行和第 4 行,因为pbanpd现在都指向同一个对象。请帮我理解。

#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 ?)
}

标签: c++classinheritancepolymorphismvirtual-functions

解决方案


函数run1是虚函数,而函数run2不是虚函数。

虚函数根据使用指针的动态类型调用,非虚函数根据使用指针的静态类型调用。

指针的静态类型pbB *.

  B b, *pb;

在这个任务之后

pb = &b;

指针的动态类型也是B *. 所以类中定义的虚函数B被调用。

在这个任务之后

pb = &d;

指针的动态类型pbB *变为 D *

所以在这个声明中

pb->run1(); //Derived (why ?)

根据指针的动态类型称为虚函数。虽然在此声明中

pb->run2(); //Base    (why ?)

根据指针的静态类型称为非虚函数。

即在使用的指针指向的对象中搜索指向虚函数指针表的指针。

此功能定义了多态行为。


推荐阅读