C++ 基础之虚函数与纯虚函数
虚函数:C++多态的基础,作用可称为晚期绑定或动态绑定。
纯虚函数:可在基类中定义纯虚函数如 :virtual int area() = 0; // = 0 告诉编译器,函数没有主体,上面的虚函数是纯虚函数。可在子类中继承改写。
#未用到虚函数的早绑定或称早期绑定_start#
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a; height = b;
}
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 :" <<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 :" <<endl; return (width * height / 2);
}
};
// 程序的主函数
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle