c++ - 混淆是指针和虚函数的内存分配

标签 c++ virtual-functions

我阅读了有关虚函数的内容,但我无法弄清楚这个概念。 在下面提到的示例中。我们正在创建一个基指针并首先分配基对象,调用函数是基类,然后分配派生对象并调用其函数。既然我们已经提到将分配哪些对象,编译器是否知道在编译期间调用哪个对象函数?我不明白为什么决定会延迟到运行时。我在这里遗漏了什么吗?

#include <iostream>
using std::cout;
using std::endl;

// Virtual function selection
class Base
{
public:
   virtual void print() const
   { 
      cout << "Inside Base" << endl; 
   }
};

class Derived : public Base
{
public:
   // virtual as well
   void print() const
   { 
      cout << "Inside Derived" << endl; 
   }
};

int main()
{
   Base b;
   Derived f;

   Base* pb = &b;  // points at a Base object
   pb->print();    // call Base::print()

   pb = &f;        // points at Derived object
   pb->print();    // call Derived::print()
}

最佳答案

在您的特定情况下,编译器可能会找出基类指针指向的对象的类型。但是虚拟调度机制是为你在编译时没有这些信息的情况而设计的。例如,

int n;
std::cin >> n;

Base b;
Derived d;

Base* pb = n == 42 ? &b : &d;

在这里,选择是根据用户输入做出的。编译器不知道 pb 将指向什么。

关于c++ - 混淆是指针和虚函数的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435519/

相关文章:

c++ - 内存分配是如何完成的

c++ - 了解从多个类派生时的虚函数

C++虚方法问题

c++ - 虚函数中的默认参数

DataGridView DefaultCellStyle 的 C++/CLI 填充

c++ - 模板成员函数上的外线 sfinae 是否可能?

c++ - 阅读(?)转义字符

C++ 访问者模式和多态性

c++ - 构造函数中的虚方法

c++ - 图像(数字/字母)识别