#include<iostream>
using namespace std;
#define PI 3.14159
class Shape
{
public:
Shape(){}
~Shape(){}
virtual void Draw() = 0;
virtual double Area() = 0;
};
class Rectangle :public Shape
{
public:
Rectangle() :a(0), b(0){} //
Rectangle(int x, int y) :a(x), b(y) {}
virtual void Draw()
{
cout << "Rectangle area:" << Area() << endl;
}
virtual double Area()
{
return a * b;
}
private:
int a;
int b;
};
class Circle :public Shape
{
public:
Circle(double x) :r(x) {}
virtual void Draw()
{
cout << "Circle area:" << Area() << endl;
}
virtual double Area()
{
return PI*r*r;
}
private:
double r;
};
class Square :public Rectangle
{
public:
Square(int length) :a(length) {}
virtual void Draw()
{
cout << "Square area:" << Area() << endl;
}
virtual double Area()
{
return a*a;
}
private:
int a;
};
int main()
{
Rectangle rect(10, 20);
Square square(10);
Circle circle(8);
Shape *p;
p = ▭
p->Draw();
p = □
p->Draw();
p = &circle;
p->Draw();
return 0;
}
这段代码是为了体会面向对象。基类Shape中的Draw()和Area()都是纯虚函数,所以Shape类是抽象类。这两个函数必须在子类中给出实现。且Shape不能实例化,所以这里是用一个指针去访问Draw和Area。
我对Rectangle类中必须给出默认构造方法Rectangle() :a(0), b(0){} .的理解是:
因为Square类继承了Rectangle类,在实例化Square的时候要调用基类的构造方法,此时应该调用不带参数的构造方法。而当Rectangle自己写了一个带参数的构造方法的时候,编译器不会在给Rectangle自动定义一个不带参数的默认构造方法了。如果不写这个行,就会出现这样的错误