重载 [ ] () 操作符
- 下标运算符运算符[ ] ()是二元运算符
- [ ]和()只能用成员函数重载,不能用友元函数重载
- [ ]运算符用于访问数据对象的元素
- 重载格式 类型 类 :: 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");
}