(1)定义抽象类Shape,在此基础上派生出圆类Circle、正方形类Square、三角形类Triangle,3个派生类都有构造函数,输入和显示信息函数Input()、Show(),计算面积的函数Area(),计算周长的函数Perim()。完成以上类的编写,在主函数中动态创建3类对象,通过基类的指针指向派生类对象,并调用派生类对象相应函数。
时间: 2023-06-01 11:02:10 浏览: 124
#include<iostream>
#include<cmath>
using namespace std;
class Shape {
protected:
double area, perim;
public:
Shape() {
area = 0;
perim = 0;
}
virtual void Input() = 0;
virtual void Show() = 0;
virtual double Area() = 0;
virtual double Perim() = 0;
};
class Circle: public Shape {
private:
double radius;
public:
Circle() {
radius = 0;
}
Circle(double r) {
radius = r;
}
void Input() {
cout << "请输入圆的半径:" << endl;
cin >> radius;
}
void Show() {
cout << "半径为:" << radius << endl;
cout << "面积为:" << area << endl;
cout << "周长为:" << perim << endl;
}
double Area() {
area = 3.14 * pow(radius, 2);
return area;
}
double Perim() {
perim = 2 * 3.14 * radius;
return perim;
}
};
class Square: public Shape {
private:
double side;
public:
Square() {
side = 0;
}
Square(double s) {
side = s;
}
void Input() {
cout << "请输入正方形的边长:" << endl;
cin >> side;
}
void Show() {
cout << "边长为:" << side << endl;
cout << "面积为:" << area << endl;
cout << "周长为:" << perim << endl;
}
double Area() {
area = pow(side, 2);
return area;
}
double Perim() {
perim = 4 * side;
return perim;
}
};
class Triangle: public Shape {
private:
double a, b, c;
public:
Triangle() {
a = 0;
b = 0;
c = 0;
}
Triangle(double aa, double bb, double cc) {
a = aa;
b = bb;
c = cc;
}
void Input() {
cout << "请输入三角形的三边长:" << endl;
cin >> a >> b >> c;
}
void Show() {
cout << "三边长分别为:" << a << "," << b << "," << c << endl;
cout << "面积为:" << area << endl;
cout << "周长为:" << perim << endl;
}
double Area() {
double p = (a + b + c) / 2;
area = sqrt(p * (p - a) * (p - b) * (p - c));
return area;
}
double Perim() {
perim = a + b + c;
return perim;
}
};
int main() {
Shape* s[3];
s[0] = new Circle();
s[1] = new Square();
s[2] = new Triangle();
for (int i = 0; i < 3; i++) {
s[i]->Input();
s[i]->Area();
s[i]->Perim();
s[i]->Show();
}
return 0;
}
阅读全文