动态绑定和静态

Dynamic binding and static

我想我在理解动态bynding时遇到了一些麻烦。

假设我们有 2 类:

class a1{ //..
virtual void print() const;
};

class a2:a1{ //...
void print() const override;
};

为什么以下是正确的:

a2 item_son;
a1 &item_father = item_son;
item_father->print();

被调用的打印是儿子的一个。

实际上,OP 确实意识到了函数 virtual 重载与非 virtual 重载的含义。但是,我得到了我的样本 运行,因此,我想发布它:

#include <iostream>

class A1 {
  public:
  virtual void print() const
  {
    std::cout << "A1::print() called." << std::endl;
  }
};

class A2: public A1 {
  public:
  void print() const override
  {
    std::cout << "A2::print() called." << std::endl;
  }
};

class B1 {
  public:
  void print() const
  {
    std::cout << "B1::print() called." << std::endl;
  }
};

class B2: public B1 {
  public:
  void print() const
  {
    std::cout << "B2::print() called." << std::endl;
  }
};

using namespace std;

int main(void)
{
  A2 a2;
  cout << "Calling a2.print(): ";
  a2.print();
  A1 &a1 = a2;
  cout << "Calling a1.print(): ";
  a1.print();
  B2 b2;
  cout << "Calling b2.print(): ";
  b2.print();
  B1 &b1 = b2;
  cout << "Calling b1.print(): ";
  b1.print();
  return 0;
}

输出:

Calling a2.print(): A2::print() called.
Calling a1.print(): A2::print() called.
Calling b2.print(): B2::print() called.
Calling b1.print(): B1::print() called.

Life demo on ideone