C++的虚函数与对象切割
2010-12-12 07:21:10 来源:WEB开发网核心提示:一道非常基础的题目,请回复下面程序的结果:#include <iostream.h>class ClassA{public: void fun1(); void fun2(); virtual void fun3();};void ClassA::fun1(){ cout <&
一道非常基础的题目,请回复下面程序的结果:
#include <iostream.h> class ClassA { public: void fun1(); void fun2(); virtual void fun3(); }; void ClassA::fun1() { cout << "ClassA.fun1"<<endl; }; void ClassA::fun2() { cout << "ClassA.fun2"<<endl; }; void ClassA::fun3() { cout << "ClassA.fun3"<<endl; }; class ClassB : public ClassA { public: void fun1(); void fun2(); virtual void fun3(); }; void ClassB::fun3() { cout << "ClassB.fun3"<<endl; }; class ClassC : public ClassB { public: void fun1(); void fun2(); virtual void fun3(); }; void ClassC::fun3() { cout << "ClassC.fun3"<<endl; }; void main() { ClassA *a[3]; ClassA a1; ClassB b1; ClassC c1; a1.fun3(); b1.fun3(); c1.fun3(); a[0] = &a1; a[1] = &b1; a[2] = &c1; cout << "virtual function array test" <<endl; for(int i=0;i<3;i++) { a[i]->fun3(); } cout << "((ClassA)&b1).fun3():"; ((ClassA*)&b1)->fun3(); //object slicing cout << "object slicing"<<endl; cout <<"((ClassA)b1).fun3():"; ((ClassA)b1).fun3(); }
[]
更多精彩
赞助商链接