父类:
关键字:virtual(虚函数),父类方法添加virtual关键字后子类可重新定义
定义纯虚函数 virtual int area() = 0; = 0 告诉编译器,函数没有主体,上面的虚函数是纯虚函数。
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
子类:
Rectangle( int a=0, int b=0):Shape(a, b) { } 这段代码表示继承并使用父类的方法
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);
}
};