ssy/c++上机3.cpp

104 lines
3.2 KiB
C++
Raw Permalink Normal View History

2024-08-05 20:42:46 +05:30
#include <iostream>
class CComplex {
private:
float real;
float imag;
public:
// 构造函数
CComplex(float r = 0.0, float i = 0.0) : real(r), imag(i) {}
// 拷贝构造函数
CComplex(const CComplex& other) : real(other.real), imag(other.imag) {}
// 赋值运算符重载
CComplex& operator=(const CComplex& other) {
real = other.real;
imag = other.imag;
return *this;
}
// 加法运算符重载
CComplex operator+(const CComplex& other) const {
return CComplex(real + other.real, imag + other.imag);
}
// 减法运算符重载
CComplex operator-(const CComplex& other) const {
return CComplex(real - other.real, imag - other.imag);
}
// 乘法运算符重载
CComplex operator*(const CComplex& other) const {
return CComplex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);
}
// 除法运算符重载
CComplex operator/(const CComplex& other) const {
float denominator = other.real * other.real + other.imag * other.imag;
if (denominator == 0.0) {
std::cerr << "错误:除数为零!" << std::endl;
return CComplex();
}
return CComplex((real * other.real + imag * other.imag) / denominator, (imag * other.real - real * other.imag) / denominator);
}
// 相等运算符重载
bool operator==(const CComplex& other) const {
return (real == other.real) && (imag == other.imag);
}
// 不等运算符重载
bool operator!=(const CComplex& other) const {
return !(*this == other);
}
// 下标运算符重载
float operator[](int index) const {
if (index == 0) return real;
else if (index == 1) return imag;
else {
std::cerr << "错误:下标越界!" << std::endl;
return 0.0;
}
}
// 打印复数
void print() const {
std::cout << "(" << real << " + " << imag << "i)";
}
// 虚析构函数
virtual ~CComplex() {}
};
int main() {
float real1, imag1, real2, imag2;
// 输入第一个复数
std::cout << "请输入第一个复数的实部:";
std::cin >> real1;
std::cout << "请输入第一个复数的虚部:";
std::cin >> imag1;
// 输入第二个复数
std::cout << "请输入第二个复数的实部:";
std::cin >> real2;
std::cout << "请输入第二个复数的虚部:";
std::cin >> imag2;
// 创建两个复数对象
CComplex a(real1, imag1);
CComplex b(real2, imag2);
// 测试运算符重载
CComplex c = a + b;
std::cout << "a + b = ";
c.print();
std::cout << std::endl;
c = a - b;
std::cout << "a - b = ";
c.print();
std::cout << std::endl;
c = a * b;
std::cout << "a * b = ";
c.print();
std::cout << std::endl;
c = a / b;
std::cout << "a / b = ";
c.print();
std::cout << std::endl;
// 测试相等和不等运算符重载
if (a == b) {
std::cout << "a 等于 b。" << std::endl;
} else {
std::cout << "a 不等于 b。" << std::endl;
}
// 测试下标运算符重载
std::cout << "a 的实部:" << a[0] << std::endl;
std::cout << "a 的虚部:" << a[1] << std::endl;
return 0;
}