C++中多态与虚函数的学习例子

多态(Polymorphism):在面向对象语言中,接口的多种不同的实现方式。也可以这样理解:在运行时,可以基类的指针来调用实现派生类中的方法。简单的一句话:允许将子类类型的指针赋值给父类类型的指针

虚函数(Virtual Function):它的作用是实现动态联编,也就是在程序的运行阶段动态地选择合适的成员函数。它是C++多态的一种表现。

 

示例

 

#include <iostream>
#include<string>
using namespace std;

class Fruit
{
 public:
  void put_Color(string str)
  {
   m_strColor = str;
  }

  string get_Color()
  {
   return m_strColor;
  }

  virtual void Draw(){};                      // Virtual Fucntion

 private:
  string m_strColor;

};

class Apple: public Fruit
{
 virtual void Draw()                          // Virtual Fucntion
 {
  cout<<"I'm an Apple"<<endl;
 }
};

class Orange: public Fruit
{
 virtual void Draw()                           // Virtual Fucntion
 {
  cout<<"I'm an Orange"<<endl;
 }
};

class Banana: public Fruit
{
 virtual void Draw()                            // Virtual Fucntion
 {
  cout<<"I'm a Banana"<<endl;
 }
};


int main()
{
 Fruit *pFruitList[3];
 pFruitList[0] = new Apple;
 pFruitList[1] = new Orange;
 pFruitList[2] = new Banana;

 for(int i=0; i<3; ++i)
  pFruitList[i]->Draw();
}

 

//运行结果

I'm an Apple

I'm an Orange

I'm a Banana

 

My Site: http://www.qingqingting.com/

My TaoBaoShop:  http://KanGuoLai.taobao.com/

 

Thank you!!

 

 

 

posted on 2010-09-17 10:23  轻轻听  阅读(502)  评论(0)    收藏  举报

导航