虚函数如果有返回类型的时候可以直接返回0。 以下为例;
getPerim() 和 getArea() 函数定义的时候都是 return 0;
#include<iostream>
#include<math.h>
#define PI 3.141592653
using namespace std;
//请编写一个抽象类Shape,在此基础上派生出类Rectangle和Circle,
//二者都有计算对象面积的函数getArea()、计算对象周长的函数getPerim()。
class Shape {
private:
double x;
double y;
double r;
public:
Shape(double xx, double yy, double rr)
{
x = xx; y = yy; r = rr;
}
virtual ~Shape() {}
virtual double getPerim() { return 0; }
virtual double getArea() { return 0; }
void virtual show() {}
double getx() {
return x;
}
double gety() {
return y;
}
double getr() {
return r;
}
};
class Rectangle :public Shape {
private:
double theta;
public:
Rectangle(double xx, double yy, double rr, double th) :Shape(xx, yy, rr)
{
theta = th;
}
virtual ~Rectangle() {}
double getPerim()
{
return getr()*cos(theta) * 4 + getr()*sin(theta) * 4;
}
double getArea() {
return getr()*cos(theta) * 2 * getr()*sin(theta) * 2;
}
void show() {
cout << "*******************矩形***************************" << endl;
double a = getr()*cos(theta), b = getr()*sin(theta);
cout << "长:" << (a>b ? a : b) * 2 << " 宽:" << (a<b ? a : b) * 2 << endl;
cout << "面积:" << getArea() << endl;
cout << "周长:" << getPerim() << endl;
}
};
class Circle :public Shape {
public:
Circle(double xx, double yy, double rr) :Shape(xx, yy, rr) {}
virtual ~Circle() {}
double getPerim() {
return 2 * PI*getr();
}
double getArea() {
return PI * getr()*getr();
}
void show() {
cout << "*********************圆****************************" << endl;
cout << "圆心:" << "(" << getx() << "," << gety() << ")" << endl;
cout << "半径:" << getr() << endl;
cout << "面积:" << getArea() << endl;
cout << "周长:" << getPerim() << endl;
}
};
int main()
{
cout << "*&*&*&*&*&*&*&*&*&* 抽象类 *&*&*&*&*&*&*&*&*&*&*&*" << endl;
Shape *s;
s = new Rectangle(3, 4, 2, PI / 6);
s->show();
delete s;
s = new Circle(3, 4, 5);
s->show();
delete s;
return 0;
}