// lesson_4.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Biology
{
public:
void grow(){ cout << "biology grow" << endl; }
};
class Animal :public Biology
{
public:
void grow(){ cout << "animal grow" << endl; }
};
class Rabbit : public Animal
{
public:
void grow(){ cout << "rabbit grow" << endl; }
};
int _tmain(int argc, _TCHAR* argv[])
{
Animal animal;
Biology * biology = &animal;
biology->grow(); //若是函数体前不加virtual 实现基类的方法
Biology * ani = new Animal;
ani->grow();
Animal * anil1 = new Rabbit;
anil1->grow();
system("pause");
return 0;
}
//
动态的多态:一个接口,多个实现,不同的对象有相同的基类,接收同一消息时,产生不同的反应
#include "stdafx.h"
#include <iostream>
using namespace std;
class Biology
{
public:
void grow(){ cout << "biology grow" << endl; }
};
class Animal :public Biology
{
public:
void grow(){ cout << "animal grow" << endl; }
};
class Rabbit : public Animal
{
public:
void grow(){ cout << "rabbit grow" << endl; }
};
int _tmain(int argc, _TCHAR* argv[])
{
Animal animal;
Biology * biology = &animal;
biology->grow(); //若是函数体前不加virtual 实现基类的方法
Biology * ani = new Animal;
ani->grow();
Animal * anil1 = new Rabbit;
anil1->grow();
system("pause");
return 0;
}
多态的注意点:
(1)virtual实现的是动态的多态
(2)实现多态,函数名,返回值,形参的个数和类型必须一样
(3)基类函数前加virtual,派生类默认声明为virtual,可以继承
(4)只有当基类指针指向派生类对象的时候,调用virtual函数,并且子类中也有该方法,才构成多态
补充:
纯虚函数和抽象类:
virtual grow() = 0; 纯虚函数
含有纯虚函数的类称为抽象类,不可以实例化