1.设计复数类Complex,实现运算符重载。要求:
(1)重载运算符“+”和“*”,使之分别能用于复数相加和相乘。
(2)重载运算符“<<”、使得复数对象能够使用“<<”运算符输出。
2.定义抽象类Geometry。在此基础上派生出类Rectangle和Circle。二者都有计算周长函数getPerim和计算面积的函数getAream。计算两者对象的周长和面积,测试动态多态性。
你自己可以先运行一下:
1.复数类 Complex 的实现和运算符重载
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} // 构造函数
// 重载 "+" 运算符用于复数相加
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 重载 "*" 运算符用于复数相乘
Complex operator*(const Complex& other) const {
return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);
}
// 重载 "<<" 运算符用于输出复数
friend ostream& operator<<(ostream& out, const Complex& c);
};
// 重载 "<<" 运算符的实现
ostream& operator<<(ostream& out, const Complex& c) {
out << c.real << " + " << c.imag << "i";
return out;
}
// 复数类测试代码
int main() {
Complex c1(3, 4), c2(1, 2);
// 输出相加结果
cout << "Sum: " << c1 + c2 << endl;
// 输出相乘结果
cout << "Product: " << c1 * c2 << endl;
return 0;
}
2.抽象类 Geometry 和派生类 Rectangle 和 Circle 的实现
#include <cmath>
#include <iostream>
using namespace std;
// 抽象基类 Geometry
class Geometry {
public:
virtual double getPerim() const = 0; // 计算周长的纯虚函数
virtual double getArea() const = 0; // 计算面积的纯虚函数
virtual ~Geometry() {} // 虚析构函数
};
// 派生类 Rectangle
class Rectangle : public Geometry {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double getPerim() const override {
return 2 * (width + height);
}
double getArea() const override {
return width * height;
}
};
// 派生类 Circle
class Circle : public Geometry {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getPerim() const override {
return 2 * M_PI * radius;
}
double getArea() const override {
return M_PI * radius * radius;
}
};
// 测试抽象类和派生类
int main() {
Geometry* shapes[2];
shapes[0] = new Rectangle(5, 10);
shapes[1] = new Circle(7);
for (int i = 0; i < 2; i++) {
cout << "Shape " << i+1 << ": Perimeter = " << shapes[i]->getPerim() << ", Area = " << shapes[i]->getArea() << endl;
delete shapes[i]; // 删除动态分配的对象
}
return 0;
}