一、完成复数类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; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录