标签:
虚函数
#include <iostream> #include <string> using namespace std; class Base { public: virtual void print_val() { cout << "base" << endl; } }; class Derived : public Base { public: void print_val() { cout << "Derived" << endl; } }; int main() { Derived d; Base ob(d); Base *pb = &d; Base &yb = d; ob.print_val(); pb->print_val(); yb.print_val(); }
运行结果:
base Derived Derived
现象
程序用了三种方式来测试虚函数的调用:基类对象、基类指针、基类引用。由结果可以看出,当用引用、指针调用虚函数是调用的是派生类的实际函数,而不是基类的虚函数。
结论
对比
#include <iostream> #include <string> using namespace std; class Base { public: void print_val() { cout << "base" << endl; } }; class Derived : public Base { public: void print_val() { cout << "Derived" << endl; } }; int main() { Derived d; Base ob(d); Base *pb = &d; Base &yb = d; ob.print_val(); pb->print_val(); yb.print_val(); }
结果:
base base base
总结
标签:
原文地址:http://www.cnblogs.com/jeakeven/p/4598731.html