C++重载双目操作符(流操作符、算术运算符、比较运算符)

重载双目操作符解决方案

如果是重载双目操作符(即为类的成员函数),就只要设置一个参数作为右侧运算量,而左侧运算量就是对象本身
note:C++规定操作符重载默认为全局性质的,即使定义在类内部,也不能访问类的私有成员,只能定义为友元函数或者通过其他方式访问私有成员。

流操作符:<< >>,将类内部的私有成员进行输入输出

  1. 使用常规成员函数
    对于>>或者<<,左侧运算量是cin或者cout,不是对象本身,如果一定要声明为常规成员函数(通过this指针访问本类的成员,可以少写一个参数,但是表达式左边的第一个参数必须是类对象,通过该类来调用成员函数),只能如下:
    #include <iostream>
    using namespace std;
    class complex
    {
    public:
    	complex(int x, int y) : real(x), imag(y) {}
    	complex() :complex(0, 0) {}
    	~complex() {}
    	ostream& operator << (ostream& cout);
    private:
    	int real;
    	int imag;
    };
    ostream& complex:: operator << (ostream& cout)
    {
    	cout << this->real << "+" << this->imag << "i" << endl;
    	return cout;
    }
    //调用
    int main()
    {
    	complex data(1, 2);
    	data << cout;//不符合习惯
    	return 0;
    }
    可以省略一个参数,但是调用时只能data<<cout;不符合习惯
  2. 常规操作,利用友元函数重载流操作符​​​​,友元函数一定程度破坏了封装性
    class complex
    { 
    public: 
        complex(int x, int y): real(x), imag(y){}
        complex():complex(0,0){}
        ~complex(){} 
        friend ostream& operator << (ostream& cout, complex& par);
    private: 
        int real;
        int imag;    
    };
    ostream& operator << (ostream& cout, complex& par)
    {
        cout << par.real << "+" << par.imag << "i" << endl;
        return cout;
    }

     

  3.  定义在类外部,使用类的成员函数暴露对类成员的访问(推荐方案,增加封装性)

    #include <iostream>
    using namespace std;
    class complex
    {
    public:
    	complex(int x, int y) : real(x), imag(y) {}
    	complex() :complex(0, 0) {}
    	~complex() {}
    	int getReal() { return real; }
    	int getImag() { return imag; }
    	void setReal(int parm) { real = parm; }
    	void setImag(int parm) { imag = parm; }
    private:
    	int real;
    	int imag;
    };
    ostream& operator << (ostream& cout, complex& par);
    ostream& operator << (ostream& cout, complex& par)
    {
    	cout << par.getReal() << " + " << par.getImag() << "i" << endl;
    	return cout;
    }
    //调用
    int main()
    {
    	complex data(1, 2);
    	cout<<data;
    	return 0;
    }

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值