在写MFC应用程序的时候,有必要搞懂虚函数和Object Slicing.
我们首先来看一个极为简单的程序:
- #include <iostream>
- using namespace std;
-
- class A
- {
- public:
- void f()
- {
- cout << "A::f" << endl;
- g();
- }
-
- void g()
- {
- cout << "A::g" << endl;
- }
-
- };
-
- class B : public A
- {
- public:
- void g()
- {
- cout << "B::g" << endl;
- }
- };
-
- int main()
- {
- B b;
- b.f(); // A::f和A::g
- ((A)b).f(); // A::f和A::g
-
- B *pb = new B;
- pb->f(); // A::f和A::g
- ((A*)(&b))->f(); // A::f和A::g
-
- return 0;
- }
现在把g函数设置为虚函数,得到程序为:
- #include <iostream>
- using namespace std;
-
- class A
- {
- public:
- void f()
- {
- cout << "A::f" << endl;
- g();
- }
-
- virtual void g()
- {
- cout << "A::g" << endl;
- }
-
- };
-
- class B : public A
- {
- public:
- virtual void g()
- {
- cout << "B::g" << endl;
- }
- };
-
- int main()
- {
- B b;
- b.f(); // A::f和B::g
- ((A)b).f(); // A::f和A::g (Object Slicing)
-
- B *pb = new B;
- pb->f(); // A::f和B::g
- ((A*)(&b))->f(); // A::f和B::g
-
- return 0;
- }