您的位置:首页 > 编程语言 > C语言/C++

《C++面向对象》C++虚函数与多态性

2012-12-06 10:53 260 查看
虚函数与多态:目的是让父类指针可以调用子类的同名方法。

1.先看源码,test.cpp

#include <iostream>
using namespace std;
namespace mytest{
  class father{
    public:
      virtual void common(){      //有无这个virtual,对引用(后边p1和p2影响)
        cout << "this is father!"  <<endl;
      };
  };

  class son: public father{
    public:
      void common(){
        cout << "this is son!" <<endl;
      };
  };
}

using namespace mytest;

int main(){
  son *s = new son();
  s->common();
  father f;
  f.common();
  father *p1 = s;
  p1->common();
  father *p2 = &f;
  p2->common();
  return 0;
}


2.g++ -o test test.cpp

3./test

看看不加virtual的结果:

this is son!
this is father!
this is father!
this is father!


看看加virtual的i结果:

this is son!
this is father!
this is son!
this is father!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: