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!!
?
?
?
轉載于:https://www.cnblogs.com/qqting/archive/2010/09/17/1829014.html
總結
以上是生活随笔為你收集整理的C++中多态与虚函数的学习例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [C++]Call virtual me
- 下一篇: PetShop的系统架构设计[转]