C++学习之运算符重载三

重载 [ ] () 操作符

  • 下标运算符运算符[ ] ()是二元运算符
  • [ ]和()只能用成员函数重载,不能用友元函数重载
  • [ ]运算符用于访问数据对象的元素
  • 重载格式 类型 类 :: operator[](类型)
  • 例如:x是类A的一个对象:x[y] ,可解释为:x.operator

  • 案例
#include<iostream>
using namespace std;
class vector
{
public:
	vector(int n)	//构造函数
	{
		v = new int[n];
		size = n;
	}
	~vector()	//析构
	{
		delete []v;
		size = 0;
	}
	//重载[]
	int& operator[](int i)
	{
		return v[i];
	}
private:
	int size;int *v;
void main()
{
	vector a(5);
	a[2] = 2;
	//int& operator[](int i)
	cout<<a[2]<<enedl;
	system("pause");
}


};

重载()

  • () 运算符用于函数调用

  • 重载格式 类型 类 :: operator() ( 表达式表 ) ;

  • 例如:x是类A的一个对象,表达式 x(arg1,arg2…)可解释为:x.operator()(arg1,arg2,…)

  • 案例

#include<iostream>
using namespace std;
class F
{
public:
	//1 重载
	int operator()(int a,int b)
	{
		return a*a + b*b;
	}
	//2 普通函数
	int add(int a,int b)
	{
		return a*a + b*b;
	}
private:
	int a;int b;	
};

void main()
{
	 //1 重载()实现2*2 + 3*3
	F f;
	f(2,3);
	//operator()(2,3)

	//2 普通函数调用
	F f2;
	f2.add(2,3);

	system("pause");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值