c++运算符重载


运算符重载也可以发生函数重载

加号运算符重载

成员函数重载+

class Person
{
private:
	int a;
	int b;
public:
	Person operator+(Person& p)
	{
		Person temp;
		temp.a = this->a + p.a;
		temp.b = this->b + p.b;
		return temp;
	}
};
int main()
{
	Person a, b, c;
	c = a.operator+(b);//可以简化为 c = a + b;
}

全局函数重载+

class Person
{
public:
	int a;
	int b;
};
//Person operator+(Person& p1,Person &p2)的函数重载可以是Person operator+(Person& p1,int num) 这样就可以实现Person类对象和普通实数的相加了
Person operator+(Person& p1,Person &p2)
{
		Person temp;
		temp.a = p1->a + p2->a;
		temp.b = p2->b + p2->b;
		return temp;
}
int main()
{
	Person a, b, c;
	c = operator+(a,b);//可以简化为 c = a + b;
}

左移运算符重载(<<)

一般用全局函数重载左移运算符

//ostream &cout 用&的原因是取一个别名 cout对象只能由一个 只能去获取地址 不能重新创建一个 所以可以把cout改成其他的 比如out 然后以后输出就可以是 out<<p;
void operator<<(ostream &cout,Person &p)
{
	cout<<"A="<<p.a<<"B="<<p.b;
}
/*但是上面的重载只能实现一个 cout<<p  不能实现 cout<<p<<p*/
/*下面这样就行了*/ // 下面函数的数据类型&也和上面使用&一样 只能获取地址 不能重新创建一个 
ostream& operator<<(ostream &cout,Person &p)
{
	cout<<"A="<<p.a<<"B="<<p.b;
	return cout;
}

++运算符重载

++操作符只能作用于变量,而不能是一个数字
a++ 结束之后 是一个常数值 所以不能++(a++)

a+++b

一般看做(a++) + b

前置递增

class New
{
	friend ostream& operator<<(ostream& cout, New ne);
public:
	New()
	{
		a = 0;
	}
/*加&的原因是 如果不使用& 则在使用++(++ne)完成第一次++ne操作之后 返回的是一个新的ne 而不是main函数里面创建的那个NEW ne了*/
	New &operator++()
	{
		a++;
		return *this;
	}
private:
	int a;
	
};
ostream& operator<< (ostream& cout,New ne)
{
	cout << ne.a;
	return cout;
}
int main()
{
	New ne;
	cout << ++ne;
	//如果是New operator++() 则 cout<<++(++ne)的结果是2 但是如果执行
	//++(++ne)
	//cout<<ne;//结果是1 因为真正对main函数中ne有效的是第一个++ne 在完成这一步之后返回的就不再是 New ne了  而是一个新的变量 所以需要加上&来引用 保证返回的是一个ne
	
}

后置递增

加int参数的目的主要是方便函数重载 int代表占位参数 可以用于区分前置和后置递增 也必须写int 其他的不行

New operator++(int)
{
New temp = *this;//也因为这里是局部变量 所以不能返回引用
a++;
return temp;
}

重载函数调用运算符(())(伪函数)

因为使用起来非常类似于函数调用 所以称为伪函数

class Stu()
{
public:
	void operator()(string a)
	{
		cout(a);
	}
}
int main()
{
	Stu stu;
	stu("hello world");

	//还可以直接通过匿名对象调用仿函数
	Stu()("hello world");
}

>>输入输出运算符重载

class A
{
    int val;
    int id;
public:
    A(int a, int b)
    {
        val = a;
        id = b;
    }
    /*类内重载*/
    ostream& operator<<(ostream& out)
    {
        cout << "类内重载:";
        out  << val <<","<<id << endl;
        return out;
    }
    friend ostream& operator << (ostream& out, const A& a);
    /*友元函数*/
};
ostream& operator << (ostream& out, const A& a)
{
    cout << "类外友元的重载:";
    out << a.val << "," << a.id << endl;
    return out;
}
int main()
{
    A a(3, 4);
    a.operator<<(cout);
    cout << a;
}

请添加图片描述

注意

运算符“=”、“[]”、“()”、“->”以及所有的类型转换运算符只能作为成员函数重载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值