运载符重载

1、运载符重载的调用形式

《返回形式》operator《运算符》(参数表)


有两种调用形式:

显示的调用:a.operator+(b)

隐士的调用: a+b

函数例子:

<span style="font-size:18px;">#include<iostream>
using namespace std;
class A
{
private:
	int n;
public:
	A(int x = 0)
	{
		n = x;
	}
	int getn()
	{
		return n;
	}
	A operator+(A a);
};
A A::operator+(A a)
{
	A temp;
	temp.n = a.n + n;
	return temp;
}

int main()
{
	A ob1(1), ob2(2), ob3, ob4;
	ob3 = ob1 + ob2;
	ob4 = ob1.operator+(ob2);
	cout << "ob3.n" << "  "<<ob3.getn() << endl;
	cout << "ob4.n" <<"\t"<< ob4.getn() << endl;
	system("pause");
	return 0;
}</span>

<span style="font-size:18px;">#include<iostream>
using namespace std;
class A
{
private:
	int n;
public:
	A(int x = 0)
	{
		n = x;
	}
	int getn()
	{
		return n;
	}
	A operator++();
	
};
A A::operator++()
{
	++n;
	return *this;
}

int main()
{
	A ob1(1);
	++ob1;
	cout << "shuchuzhi" << ob1.getn() << endl;
	ob1.operator++();
	cout << "bianhuan" << ob1.getn() << endl;
	system("pause");
	return 0;
}</span>

2、运算符重载是类的友元函数是


调用格式:

friend <返回类型> operator<运算符>(参数表)

在类外定义

《返回类型》 operator<运算符》(参数表)


友元函数可以调用类的私有成员,相当于类的公有成员

显示的调用:

operator+(a,b)

隐士的调用:a+b

<span style="font-size:18px;">#include<iostream>
using namespace std;
class A
{
private:
	int a, b;
public:
	A(int x = 0, int y = 0)
	{
		a = x;
		b = y;
	}
	int geta()
	{
		return a;
	}
	int getb()
	{
		return b;
	}
	friend A operator+(A p, A q);
};
A operator+(A p, A q)
{
	A temp;
	temp.a = p.a + q.a;
	temp.b = p.b + q.b;
	return temp;
}
int main()
{
	A ob1(1, 2), ob2(3, 4), ob3, ob4;
	ob3 = ob1 + ob2;
	ob4 = operator+(ob1, ob2);
	cout << ob3.geta() << " " << ob3.getb() << endl;
	cout << ob4.geta() << " " << ob4.getb() << endl;
	system("pause");
	return 0;

}</span>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值