【题目】
- 定义复数类,Complex类,包含double类型的数据成员,用于存储实部和虚部的值;
- 定义构造函数:默认构造函数(实部、虚部均为0),带2个参数的构造函数,将double类型数据转换成对象的转换构造函数;
- 定义类型转换函数,实现对象到float类型的转换;
- 重载+运算符:实现对象相加,整型加对象,对象加整型;
- 重载<<运算符和>>运算符:实现对象的输入和输出;
编写主函数,在主函数中使用和验证以上实现的功能的正确性(编写语句把上面的函数都用一遍)。
【代码】
#include<iostream>
using namespace std;
class complax {
public:
complax()
{
real = 0;
image = 0;
}
complax(double r, double i) :real(r), image(i) {}
complax operator +(complax& c1);
complax operator -(complax& c1);
complax operator *(complax& c1);
complax operator /(complax& c1);
friend complax operator+(int& i, complax& c1);
complax operator+(int& i);
void display();
private:
double real;
double image;
};
complax complax::operator +(complax& c1)
{
complax c;
c.real = real + c1.real;
c.image = image + c1.image;
return c;
}
complax complax::operator-(complax& c1)
{
complax c;
c.real = real - c1.real;
c.image = image - c1.image;
return c;
}
complax complax::operator*(complax& c1)
{
complax c;
c.real = (real * c1.real - image * c1.image);
c.image = (image * c1.real + real * c1.image);
return c;
}
complax complax::operator/(complax& c1)
{
complax c;
double denominator = c1.real * c1.real + c1.image * c1.image;
c.real = (real * c1.real + image * c1.image) / denominator;
c.image = (image * c1.real - real * c1.image) / denominator;
return c;
}
complax operator +(int& i, complax& c1)
{
return complax(i + c1.real, c1.image);
}
complax complax::operator+(int& i)
{
complax c;
c.real = i + real;
c.image = image;
return c;
}
void complax::display()
{
cout << real << "+" << image << "i" << endl;
}
int main()
{
complax a(10, 2), b(2, 3), c;
cout << "元数据为:";
a.display();
b.display();
cout << "计算结果为(顺序依次为复数与复数的加减乘除以及整数与复数的加法)" << endl;
c = a + b;
c.display();
c = a - b;
c.display();
c = a * b;
c.display();
c = a / b;
c.display();
int i = 5;
c = i + a;
c.display();
c = a + i;
c.display();
return 0;
}
【实验结果截图】
CUST 2021届