关键词搜索

源码搜索 ×
×

C++虚函数与Object Slicing

发布2013-06-01浏览8542次

详情内容

        在写MFC应用程序的时候,有必要搞懂虚函数和Object Slicing. 

        我们首先来看一个极为简单的程序:

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6. void f()
  7. {
  8. cout << "A::f" << endl;
  9. g();
  10. }
  11. void g()
  12. {
  13. cout << "A::g" << endl;
  14. }
  15. };
  16. class B : public A
  17. {
  18. public:
  19. void g()
  20. {
  21. cout << "B::g" << endl;
  22. }
  23. };
  24. int main()
  25. {
  26. B b;
  27. b.f(); // A::f和A::g
  28. ((A)b).f(); // A::f和A::g
  29. B *pb = new B;
  30. pb->f(); // A::f和A::g
  31. ((A*)(&b))->f(); // A::f和A::g
  32. return 0;
  33. }
       现在把g函数设置为虚函数,得到程序为:

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6. void f()
  7. {
  8. cout << "A::f" << endl;
  9. g();
  10. }
  11. virtual void g()
  12. {
  13. cout << "A::g" << endl;
  14. }
  15. };
  16. class B : public A
  17. {
  18. public:
  19. virtual void g()
  20. {
  21. cout << "B::g" << endl;
  22. }
  23. };
  24. int main()
  25. {
  26. B b;
  27. b.f(); // A::f和B::g
  28. ((A)b).f(); // A::f和A::g (Object Slicing)
  29. B *pb = new B;
  30. pb->f(); // A::f和B::g
  31. ((A*)(&b))->f(); // A::f和B::g
  32. return 0;
  33. }

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载