永发信息网

求一个复数计算器,要求实现复数的加减乘除, 1.定义一个类Complex 2.声明所需成员函数和友

答案:1  悬赏:70  手机版
解决时间 2021-03-10 23:39
求一个复数计算器,要求实现复数的加减乘除,
1.定义一个类Complex
2.声明所需成员函数和友元函数,输入远算符>>和输出运算符<<,并对加减乘除运算符进行重载
3.定义各类成员函数
跪求了,新手,不怎么理解,求例子
最佳答案
#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(double r = 0, double i = 0) : real_(r), imag_(i) { }
    Complex(const Complex &c):real_(c.real_), imag_(c.imag_) {    }
    ~Complex() {}
    double real() const { return real_; }
    double imag() const { return imag_; }
    void real(double r) { real_ = r; }
    void imag(double i) { imag_ = i; }
    void reset(double r, double i) { real_ = r; imag_ = i; }
    Complex operator+(const Complex &c);
    Complex operator-(const Complex &c);
    Complex operator*(const Complex &c);
    Complex operator/(const Complex &c);
    Complex& operator=(const Complex &c);
    friend ostream& operator<<(ostream &os, Complex &c);
    friend istream& operator>>(istream &is, Complex &c);
private:
    double real_;
    double imag_;
};
Complex Complex::operator+(const Complex &c) {
    return Complex(real_ + c.real_, imag_ + c.imag_);
}
Complex Complex::operator-(const Complex &c) {
    return Complex(real_-c.real_, imag_-c.imag_);
}
Complex Complex::operator*(const Complex &c) {
    return Complex((real_*c.real_ - imag_*c.imag_), (imag_*c.real_ + real_*imag_));
}
Complex Complex::operator/(const Complex &c) {
    return Complex(((real_*c.real_ + imag_*c.imag_) / (c.real_*c.real_+ c.imag_*c.imag_)), 
        (imag_*c.real_-real_*c.imag_) / (c.real_*c.real_+c.imag_*c.imag_));
}
Complex& Complex::operator=(const Complex &c) {
    real_ = c.real_; imag_ = c.imag_;
    return *this;
}
ostream& operator<<(ostream &os, Complex &c) {
    os << c.real_;
    if (c.imag_ >= 0)  os << "+";
    os << c.imag_ << "i" << endl;
    return os;
}
istream& operator>>(istream &is, Complex &c) {
    is >> c.real_ >> c.imag_;
    return is;
}
int main()
{
    Complex c;
    cout << c;
    Complex c2(1, 20);
    cout << c2;
    Complex c3(1, -20);
    cout << c3;
    Complex c4 = c2 * c3;
    cout << c4;
    Complex c5 = c2 - c3;
    cout << c5;
    Complex c6;
    c6 = c5;
    cout << c6;
    Complex c7 = c2 + c3;
    cout << c7;
    Complex c8 = c2 / c3;
    cout << c8;
}
这是最简单的例子了。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
托管中心起名
送初一女孩生日礼物什么好
百乐塑料百货超市地址在哪,我要去那里办事
下列各句中括弧内成语的使用,恰当的一句是()
电脑桌面显示怎么缩小
沈阳昊诚开关设备公司在什么地方啊,我要过去
跪求与yan xi 谐音的英文名
我是土木工程系工程造价专业的一名学生,现在
谁能从哲学角度解释一下人为什么会感到寂寞?
思烤者在什么地方啊,我要过去处理事情
15版的美利达公爵600好吗 有14 13好吗,为什
沪牌车在异地违章可以使用上海牡丹卡吗?
来疯直播间里的接龙是什么意思?
《顺藤而上的你》29集在勇怕鬼唱的歌叫什么名
河北省衡水市武邑中学教育水平,生活标准(一
推荐资讯
下列各项中,既影响营业利润又影响利润总额的
一个鱼一个各念什么
观音塘小区怎么去杭州市西溪路719号杭州第一
求科普 魔灵召唤中的完美召唤是什么意思
2016福建省专升本。经济类270分。想读金融的
7除以2打一成语
单选题材料与人类生活、生产等方面紧密相关,
格华装饰我想知道这个在什么地方
天弘基金 已收到短信确认赎回 支付宝一直没收
1994四月初八出生的女孩子命运如何
我的是win764位安装.net4.0未成功以前也未安
一个爱你的男人总在你面前说累是什么意思?
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?