分别为正方形、 矩形、三角形构建类Square、Rectangle、Triangle,分别包含各自的边长,用doulble 型数据表示。每个类都至少包含4个西数成员,函数init用于设置图形的边长,函数perimeter用来计算图形的周长,函数area用来计算图形的面积,函数show用于显示图形的类别(方形、矩形或三角形)、周长和面积。编程分别显示一个方形、一个短形、一个三角形的周长和面积。思考并回答,能否将3个类合并成一个类,如果能,怎么做?如果不能,为什么?
时间: 2024-02-12 10:06:26 浏览: 183
以下是实现三个类的代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Square {
private:
double side;
public:
void init(double s) {
side = s;
}
double perimeter() {
return 4 * side;
}
double area() {
return side * side;
}
void show() {
cout << "Shape: Square" << endl;
cout << "Perimeter: " << perimeter() << endl;
cout << "Area: " << area() << endl;
}
};
class Rectangle {
private:
double length;
double width;
public:
void init(double l, double w) {
length = l;
width = w;
}
double perimeter() {
return 2 * (length + width);
}
double area() {
return length * width;
}
void show() {
cout << "Shape: Rectangle" << endl;
cout << "Perimeter: " << perimeter() << endl;
cout << "Area: " << area() << endl;
}
};
class Triangle {
private:
double a;
double b;
double c;
public:
void init(double x, double y, double z) {
a = x;
b = y;
c = z;
}
double perimeter() {
return a + b + c;
}
double area() {
double p = perimeter() / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
void show() {
cout << "Shape: Triangle" << endl;
cout << "Perimeter: " << perimeter() << endl;
cout << "Area: " << area() << endl;
}
};
int main() {
Square s;
s.init(5);
s.show();
Rectangle r;
r.init(3, 4);
r.show();
Triangle t;
t.init(3, 4, 5);
t.show();
return 0;
}
```
输出结果:
```
Shape: Square
Perimeter: 20
Area: 25
Shape: Rectangle
Perimeter: 14
Area: 12
Shape: Triangle
Perimeter: 12
Area: 6
```
可以将三个类合并成一个类,因为它们都具有计算周长和面积的方法,并且都是二维图形。我们可以将图形的类型作为类的一个成员变量,通过不同的初始化方法来设置不同的图形类型和边长。以下是合并后的代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
private:
int type; // 0: Square, 1: Rectangle, 2: Triangle
double a, b, c;
public:
void initSquare(double s) {
type = 0;
a = b = c = s;
}
void initRectangle(double l, double w) {
type = 1;
a = b = l;
c = w;
}
void initTriangle(double x, double y, double z) {
type = 2;
a = x;
b = y;
c = z;
}
double perimeter() {
switch(type) {
case 0:
return 4 * a;
case 1:
return 2 * (a + c);
case 2:
return a + b + c;
}
}
double area() {
switch(type) {
case 0:
return a * a;
case 1:
return a * c;
case 2: {
double p = perimeter() / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
}
}
void show() {
switch(type) {
case 0:
cout << "Shape: Square" << endl;
break;
case 1:
cout << "Shape: Rectangle" << endl;
break;
case 2:
cout << "Shape: Triangle" << endl;
break;
}
cout << "Perimeter: " << perimeter() << endl;
cout << "Area: " << area() << endl;
}
};
int main() {
Shape s, r, t;
s.initSquare(5);
s.show();
r.initRectangle(3, 4);
r.show();
t.initTriangle(3, 4, 5);
t.show();
return 0;
}
```
输出结果和之前相同,但代码更简洁。
阅读全文