一、完成复数类CComplex的定义,(包括real和image两个double型数据成员)
●包括构造函数,print()打印数据成员值的成员函数.
● 并用成员函数重载 ‘=’赋值运算符和前、后‘++’运算符,用友元函数重载双目‘+’和‘-’运算符.
二、在主函数中分别进行以下测试 :
●对象=对象+对象;
●对象=对象-对象;
●++对象;
并分别调用print函数打印对象数据成员值
C++重载的相关问题
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
4条回答 默认 最新
- 技术专家团-小桥流水 2022-09-21 08:36关注
代码如下:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; class CComplex { private: double real, image; public: CComplex(double r = 0, double i = 0) { real = r; image = i; } ~CComplex() {} //友元函数+ friend CComplex& operator +(CComplex& c1, CComplex& c2) { CComplex t; t.real = c1.real + c2.real; t.image= c1.image + c2.image; return t; } friend CComplex& operator -(CComplex& c1, CComplex& c2) { CComplex t; t.real = c1.real - c2.real; t.image = c1.image - c2.image; return t; } //成员函数= CComplex& operator =(CComplex& c) { CComplex t; t.real = c.image; t.image = c.image; } //前置++ CComplex operator ++() { this->real += 1; this->image += 1; return *this; } //后置++ CComplex operator ++(int) { CComplex c(this->real, this->image); this->real += 1; this->image += 1; return c; } //前置-- CComplex operator --() { this->real -= 1; this->image -= 1; return *this; } //后置-- CComplex operator --(int) { CComplex c(this->real, this->image); this->real -= 1; this->image -= 1; return c; } void print() { if (image > 0) cout << real << "+" << image << "i"; else if (image == 0) cout << real; else cout << real << image << "i"; } }; int main() { CComplex a(3, 5), b(5, 3); cout << "a: "; a.print(); cout << endl << "b: "; b.print(); cout << endl << "a+b= "; CComplex c = a + b; c.print(); cout << endl << "a-b= "; CComplex d = a - b; d.print(); cout << endl << "++a : "; ++a; a.print(); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 网络科学导论,网络控制
- ¥15 metadata提取的PDF元数据,如何转换为一个Excel
- ¥15 关于arduino编程toCharArray()函数的使用
- ¥100 vc++混合CEF采用CLR方式编译报错
- ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
- ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
- ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
- ¥50 如何openEuler 22.03上安装配置drbd
- ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
- ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)