动态绑定和静态

时间:2018-02-18 13:59:59

标签: c++ dynamic-binding

我想我在理解动态修正方面遇到了一些麻烦。

假设我们有两个班级:

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

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

为什么以下情况属实:

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

打印出来的是儿子之一。

1 个答案:

答案 0 :(得分:0)

实际上,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