C++:运算符重载

七、运算符重载

●意义:给予运算符新的意义,使其能够支持自定义类型的操作.

●运算符重载还可以再发生函数重载.

●运算符分为:单目运算符(一个操作数)双目运算符(两个操作数) |三目运算符.(三个操作数)

●注意:运算符重载后的操作数不能改变,不能重载内置数据类型(float、int等..)

●语法:

<类型(返回值)> operator<运算符>(<参数1>...)

{

}

例如:

void operator+(int . _n1)

{

}

1、成员运算符重载:在类中进行运算符重载

调用运算符的对象要算一个操作数.

#include <iostream>
using namespace std;
class Data
{
public:
    Data():_n1(0), _f1(0.0f)
    {
    }
    Data(int n, float f):_n1(n), _f1(f)
    {
    }

    Data operator+(const Data &d)
    {
        Data temp;
        temp._n1 = this->_n1 + d._n1;
        temp._f1 = this->_f1 + d._f1;
        return temp;
    }

    Data & operator+(const int &n)
    {
        this->_n1 += n;
        return *this;
    }

    Data & operator+(const double &f)
    {
        this->_f1 += f;
        return *this;
    }

    void DataValue() const
    {
        cout << "_n1: " << _n1 << endl;
        cout << "_f1: " << _f1 << endl;
    }
    int _n1;
    float _f1;
};

Data & operator+(const int &n, Data &d)
{
    d._n1 = d._n1 + n;
    return d;
}

void test01()
{
    Data d1(4, 9.23);
    Data d2(2, 7.34);
   
    d1 = d1 + d2;    // d1.operator+(d2);
    //d2 = d1.operator+(d2);
    d1 + 45;  // d1.operator+(45) == d1 + 45;
    d2 + 5.67;

    6 + d1; // operator+(const int a, Data& d);

    d1.DataValue();
}

int main()
{
    test01();
    return 0;
}


2、全局运算符重载:在所有类外进行运算符重载

根据参数顺序来决定运算符的操作数,第一个参数作为运算符左操作数, 第二个参数作为运算符右操作数,

#include <iostream>
#include <ostream>
using namespace std;

class Person
{
	public:
		Person():p_name(""),p_age(0)
		{
			
		}
		Person(string name,int age):p_name(name),p_age(age)
	{

	}


#if 0
		void operator<<(Person &p)
		{
			cout<<"姓名"<<p.p_name<<endl;
			cout<<"年龄"<<p.p_age<<endl;
		}
#endif
		string p_name;
		int p_age;

};

ostream & operator<<(ostream &out,const Person &p)
{
	out<<"姓名"<<p.p_name<<endl;
	out<<"年龄"<<p.p_age<<endl;
	return out;
}

void test01()
{
	Person p1("zs",12);
	cout<<p1<<endl;
}

int main(int argc, char *argv[])
{
	test01();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

এ᭄星辰

混口饭吃。。。。。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值