如果虚函数在基类与子类名字相同,而参数类型不同不会进行迟后联编
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;