C++学习笔记(十一)——多态性
多态性:一个成员函数在父类及子类中的多种形态,即父类和子类可以拥有同一个函数(名称和参数都相同),但是功能不同的函数。
这意味着调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。
关键词:virtual
在成员函数前加上virtual表示虚函数
使用:在父类和子类的函数前都加上virtual,这样在调用函数时,会分别执行不同的函数
一个多态的例子:
#include <cstdio>
#include <iostream>
using namespace std;
class Shape
{
//只能在子类中访问
protected:
int width,height;
public:
Shape(int a=0,int b=0)
{
width=a;
height=b;
}
//在成员函数前加上virtual表示虚函数
virtual int area()
{
cout << "Parent class area :" << endl;
return 0;
}
};
//矩形面积
class Rectangle:public Shape
{
public:
Rectangle(int a=0,int b=0):Shape(a,b) {}
int area()
{
cout << "Rectangle class area :" << width*height << endl;
return (width*height);
}
};
//三角形面积
class Triangle:public Shape
{
public:
Triangle(int a=0,int b=0):Shape(a,b) {}
int area ()
{
cout << "Triangle class area :" << width*height/2 << endl;
return (width*height/2);
}
};
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape=&rec;
shape->area();
shape=&tri;
shape->area();
return 0;
}
posted on 2018-08-07 00:22 Radium_1209 阅读(119) 评论(0) 收藏 举报
浙公网安备 33010602011771号