C++学习013多态



何为多态
面向对象最要的特征之一就是多态,而纯虚函数是实现多态的主要方式。它可以提供一个通过用的接口,同样调用一个方法,

由于运算对象不同,方法也不同,这也就是所谓的动态绑定。

 

 

#include <iostream>
#include <stdio.h>
using namespace std;

class Animal
{
public:
    virtual void Cry()=0;

};
/*
void Animal::Cry()
{
    cout<<"base class"<<endl;
}
*/
class Dog:public Animal
{
public:
    virtual void Cry()
    {
        cout<<"wang,wang"<<endl;
    }
};
class Cat:public Animal
{
public:
    virtual void Cry()
    {
        cout<<"miao miao"<<endl;

    }
};

int main()
{
    Animal* animalone = new Dog;
    animalone->Cry();
    delete animalone;
    animalone = new Cat;
    animalone->Cry();

    Dog dog;
    dog.Cry();
    Cat cat;
    cat.Cry();



    return 0;
}

 

 

 

posted @ 2016-08-13 12:04  DreamDog  阅读(136)  评论(0编辑  收藏  举报