条件:
(1)派生类含有基类的重写函数;
(2)基类对象有派生类对象初始化(指针,引用,赋值);
结果:
基类对象调用重写函数时只调用基类函数
结论:
如何让编译器知道基类对象的真正类型,从而调用对应类型的成员,由此产生了多态的需求 , 即在重写函数前加virtual.
#include <iostream> using namespace std; class Parent { public: Parent(int A) { this->a = A; } void print() { cout << "a=" << a<<endl; } private: int a; }; class Child :public Parent { public: Child(int B) :Parent(10) { this->b = B; } void print() { cout << "b=" << b << endl; } private: int b; }; int main() { Parent *p2 = NULL; Child ch(50); p2 = &ch;//用父类指针指向子类对象 p2->print(); Parent &p3 = ch;//用子类对象初始化父类引用 p3.print();
}
输出结果均为:a=10;a=10;
用virtual 修饰print()函数后:
#include <iostream> using namespace std; class Parent { public: Parent(int A) { this->a = A; } virtual void print() { cout << "a=" << a<<endl; } private: int a; }; class Child :public Parent { public: Child(int B) :Parent(10) { this->b = B; } void print() { cout << "b=" << b << endl; } private: int b; }; int main() { Parent *p2 = NULL; Child ch(50); p2 = &ch; p2->print(); Parent &p3 = ch; p3.print(); }
输出结果均为:b=50;b=50;