cainiao1.0 2022-03-24 21:36 采纳率: 100%
浏览 10
已结题

运算符重载友元函数的调用

img

不理解关于友元函数,函数有两个参数,但是在调用时,可以直接c1+c2,结果和operator(c1,c2)一样。

#include<iostream>
using namespace std;
class Complex {//复数类
    friend Complex operator+(const Complex& c1, const Complex& c2);
    friend void show(const Complex& c);
private:
    double real;//实部
    double imag;//虚部
public:
    Complex() { real = imag = 0; }
    Complex(double re) { real = re;imag = 0; }
    Complex(double re, double im) { real = re;imag = im; }
};
Complex operator + (const Complex& c1, const Complex& c2) {
    return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
void show(const Complex& c) {
    if (c.imag > 0)
    {
        cout << c.real << "+" << c.imag << "i";
    }
    else if (c.imag < 0)
    {
        cout << c.real << c.imag << "i";
    }
    else
    {
        cout << c.real;
    }
}
int main() {
    Complex c1(4.0, -1.0);
    Complex c2(-1.0, 3.0);
    Complex c4;
    c4 = c1 + c2;
    show(operator+(c1, c2));//和c4输出结果一样  operator+(a,b)=a+b;?
    show(c4);
    show(operator+(c1, 9.0));
    return 0;
}

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 4月1日
    • 创建了问题 3月24日

    悬赏问题

    • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
    • ¥15 ArcGIS批量裁剪
    • ¥15 labview程序设计
    • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
    • ¥15 Cloudreve保存用户组存储空间大小时报错
    • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
    • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
    • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
    • ¥15 android 集成sentry上报时报错。
    • ¥15 抖音看过的视频,缓存在哪个文件