6-1 使用成员函数重载复数类的运算符+ (5 分)

类Complex声明了一个复数类,有两个数据成员realPart(代表复数的实部)和imgPart(代表复数的虚部),并定义了成员函数实现了重载运算符“+”以实现两个复数对象的相加操作。成员函数Show用来输出复数的实部和虚部。请完成对运算符“+”的重载操作。

函数接口定义:

Complex& Complex::operator+(Complex& com);
参数com为复数类Complex的对象的引用,函数的返回值为当前对象与com对象相加后的值。

裁判测试程序样例:

#include<iostream>
using namespace std;

class Complex {
public:
    Complex(double realPart = 0, double imgPart = 0) {
        this->realPart = realPart;
        this->imgPart = imgPart;
    }
    Complex& operator+(Complex& com);
    void Show() {
        cout << realPart << " " << imgPart << endl;
    }
private:
    double realPart, imgPart;
};
int main() {
    int r1, i1;            //第1个复数对象的实部和虚部
    int r2, i2;            //第1个复数对象的实部和虚部
    cin >> r1 >> i1;
    cin >> r2 >> i2;
    Complex c1(r1, i1);    //构造第1个复数对象c1
    Complex c2(r2, i2);    //构造第2个复数对象c2
    c1 = c1 + c2;
    c1.Show();

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

3 4
10 20

输出样例:

13 24

代码

Complex& Complex::operator+(Complex& c1) {
    c1.realPart += this->realPart;
    c1.imgPart += this->imgPart;
    return c1;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是复数类成员函数重载运算符的示例: ```c++ class Complex { private: double real; double imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} Complex operator+(const Complex& c) const { return Complex(real + c.real, imag + c.imag); } Complex operator-(const Complex& c) const { return Complex(real - c.real, imag - c.imag); } Complex operator*(const Complex& c) const { return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real); } Complex operator/(const Complex& c) const { double r = c.real * c.real + c.imag * c.imag; return Complex((real * c.real + imag * c.imag) / r, (imag * c.real - real * c.imag) / r); } Complex operator+=(const Complex& c) { real += c.real; imag += c.imag; return *this; } Complex operator-=(const Complex& c) { real -= c.real; imag -= c.imag; return *this; } Complex operator*=(const Complex& c) { double r = real * c.real - imag * c.imag; double i = real * c.imag + imag * c.real; real = r; imag = i; return *this; } Complex operator/=(const Complex& c) { double r = c.real * c.real + c.imag * c.imag; double nreal = (real * c.real + imag * c.imag) / r; double nimag = (imag * c.real - real * c.imag) / r; real = nreal; imag = nimag; return *this; } bool operator==(const Complex& c) const { return real == c.real && imag == c.imag; } bool operator!=(const Complex& c) const { return !(*this == c); } }; ``` 这个示例中,复数类有四个基本的运算符:加、减、乘、除。每个运算符都返回一个新的复数对象,而不是修改当前对象。此外,还有四个复合赋值运算符(+=、-=、*=、/=),它们修改当前对象并返回它。最后,还有两个比较运算符(== 和 !=),它们比较两个复数对象的实部和虚部是否相等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值