栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++运算符的重载 operator和friend的使用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++运算符的重载 operator和friend的使用

写复数加减法的时候看到的运算符的重载以及配合友元friend的使用

#include 
using namespace std;


class Complex
{
private:
    double real;
    double imag;
public:
    Complex(){}
    Complex(double real, double imag):real(real), imag(imag) {}

    void show_num(void) const
    {
        if(real != 0)
            cout << real;
        if(imag != 0)
        {
            if(imag < 0)
                cout << imag << "i";
            else
                cout << "+" << imag << "i";
        }
        cout << endl;
    }

    //重载运算符    两种写法
    //第一种使用friend以全局(友元)方式重载  两个参数都作为操作数
    //第二种不以全局(友元)方式重载  则只能用传一个参数    第一个操作数则是当前类的对象
    

    //加法:(a+bi)+(c+di)=(a+c)+(b+d)i
    Complex operator+(const Complex& c) const
    {
        return Complex(real + c.real, imag + c.imag);
    }

    //减法:(a+bi)-(c+di)=(a-c)+(b-d)i
    Complex operator-(const Complex& c) const
    {
        return Complex(real - c.real, imag - c.imag);
    }

    //乘法:(a+bi)*(c+di)=(ac-bd)+(ad+bc)i
    Complex operator*(const Complex& c) const
    {
        return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
    }
    
    //声明全局函数为友元函数    << >>只能以全局函数方式重载
    friend ostream& operator<<(ostream& os, const Complex& c)
    {
        os << c.real << "+" << c.imag << "i";
        return os;  //要有返回值
    }

    friend istream& operator>>(istream& is, Complex& c)
    {
        is >> c.real >> c.imag;
        return is;  //要有返回值
    }
};

//重载前++后++
class Int
{
public:
    Int(const int& n = 0):n(n){};

    //前++返回左值 需要加引用
    Int& operator++(void)
    {
        ++n;
        return *this;
    }

    //为了防止歧义,使用哑元    后++返回右值
    Int operator++(int)
    {
        Int tmp(*this);
        ++n;
        return tmp;
    }

    Int& operator--(void)
    {
        --n;
        return *this;
    }

    Int operator--(int)
    {
        Int tmp(*this);
        --n;
        return tmp;
    }

    friend ostream& operator<<(ostream& os, const Int a)
    {
        os << a.n;
        return os;
    }

private:
    int n;
};

int main(int argc, char *argv[])
{
    Complex num1(1, 2);
    Complex num2(2, 3);
    Complex num3(3, 3);
    cin >> num3;
    cout << num3 << endl;
    cout << "------------" << endl;
    Int a1(1024);
    Int a2 = a1++;
    cout << a2 << endl;
    cout << a1 << endl;
    cout << "-----------" << endl;
    a2 = ++a1;
    cout << a2 << endl;
    cout << a1 << endl;
    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1030422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号