class Base
{
public:
    virtual void Show(int x)
    {
        cout << "In Base class, int x = " << x << endl;
    }
};

class Derived : public Base
{
public:
    virtual void Show(float x)
    {
        cout << "In Derived, float x = " << x << endl;
    }
};

void test (Base &b)
{
    int i = 1;
    b.Show(i);
    
    float f = 2.0;
    b.Show(f);
}

int main(int argc, char *argv[])
{
    Base bc;
    Derived sc;
    test(bc);
    test(sc);
 
    return 0;
}

如果虚函数在基类与子类中出现的仅仅是名字的相同,而参数类型不同,或者返回类型不同,即使写上了virtual关键字,也不进行迟后联编。

因此上述输出为:

   In Base class, int x = 1;
   In Base class, int x = 2;
   In Base, int x = 1;
   In Base, int x = 2;

 

相关文章:

  • 2022-12-23
  • 2021-11-17
  • 2022-12-23
  • 2021-11-24
  • 2021-10-14
  • 2021-07-08
  • 2022-12-23
  • 2021-09-02
猜你喜欢
  • 2022-01-06
  • 2021-05-10
  • 2021-12-20
  • 2021-09-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案