用C++实现下面的功能。1、定义复数类COMPLEX,并用成员函数为复数类COMPLEX重载加、减及赋值运算符操作。2、15. 写一个程序,定义一个抽象类Shape,由它派生3个类:Square(正方形)、Trapezoid(梯形)和Triangle三角形。用虚函数分别计算几种图形面积、并求它们的和。要求用基类指针数组,使它每一个元素指向一个派生类对象。
时间: 2024-03-23 10:39:22 浏览: 14
好的,我来回答你的问题。
对于第一个问题,这里给出 COMPLEX 类的实现代码:
```cpp
class COMPLEX {
private:
double real;
double imag;
public:
COMPLEX(double r = 0, double i = 0) : real(r), imag(i) {}
COMPLEX operator+(const COMPLEX& rhs) const {
return COMPLEX(real + rhs.real, imag + rhs.imag);
}
COMPLEX operator-(const COMPLEX& rhs) const {
return COMPLEX(real - rhs.real, imag - rhs.imag);
}
COMPLEX& operator=(const COMPLEX& rhs) {
real = rhs.real;
imag = rhs.imag;
return *this;
}
};
```
对于第二个问题,这里给出 Shape 类及其三个派生类的实现代码:
```cpp
class Shape {
public:
virtual double getArea() const = 0;
};
class Square : public Shape {
private:
double side;
public:
Square(double s) : side(s) {}
double getArea() const override {
return side * side;
}
};
class Trapezoid : public Shape {
private:
double top, bottom, height;
public:
Trapezoid(double t, double b, double h) : top(t), bottom(b), height(h) {}
double getArea() const override {
return (top + bottom) * height / 2;
}
};
class Triangle : public Shape {
private:
double base, height;
public:
Triangle(double b, double h) : base(b), height(h) {}
double getArea() const override {
return base * height / 2;
}
};
```
接下来是主程序的实现代码:
```cpp
int main() {
const int N = 3;
Shape* shapes[N] = { new Square(2), new Trapezoid(1, 3, 2), new Triangle(4, 3) };
double totalArea = 0;
for (int i = 0; i < N; ++i) {
totalArea += shapes[i]->getArea();
}
std::cout << "The total area is: " << totalArea << std::endl;
for (int i = 0; i < N; ++i) {
delete shapes[i];
}
return 0;
}
```
运行结果为:
```
The total area is: 12.5
```
这里我们用了一个基类指针数组,将三个派生类的对象指针存储在其中,然后通过遍历数组,调用每个对象的虚函数 getArea() 来计算面积,并累加得到总面积。最后别忘了释放内存。