重载数组下标运算符"[]":
#include <iostream>
using namespace std;
class Vector
{
public:
Vector(int a1, int a2, int a3, int a4)
{
m_nGril[0] = a1 ; m_nGril[1] = a2 ;
m_nGril[2] = a3 ; m_nGril[3] = a4 ;
}
int& operator[](int nIndex) ; // 重载数组下标运算符"[]"
private:
int m_nGril[4] ;
};
//重载数组下标运算符"[]":
int& Vector::operator[](int nIndex)
{
if (nIndex < 0 || nIndex >= 4) // 数组越界检查
{
cout << "数组下标越界!" << endl ;
return m_nGril[0] ;
}
return m_nGril[nIndex];
}
//测试代码:
int main()
{
Vector vt(0, 1, 2, 3) ;
cout << vt[2] << endl ;
vt[3] = vt[2] ;
cout << vt[3] << endl ;
vt[2] = 22 ;
cout << vt[2] << endl ;
system("Pause");
return 0 ;
}
重载圆括号运算符"()":
#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix(int, int) ;
int& operator()(int, int) ; // 重载圆括号运算符"()"
private:
int * m_nMatrix ;
int m_nRow, m_nCol ;
};
Matrix::Matrix(int nRow, int nCol)
{
m_nRow = nRow ;
m_nCol = nCol ;
m_nMatrix = new int[nRow * nCol] ;
for(int i = 0 ; i < nRow * nCol ; ++i)
{
*(m_nMatrix + i) = i ;
}
}
//重载圆括号运算符"()":
int& Matrix::operator()(int nRow, int nCol)
{
return *(m_nMatrix + nRow * m_nCol + nCol) ; //返回矩阵中第nRow行第nCol列的值
}
//测试代码:
int main()
{
Matrix mtx(10, 10) ; //生成一个矩阵对象aM
cout << mtx(3, 4) << endl ; //输出矩阵中位于第3行第4列的元素值
mtx(3, 4) = 35 ; //改变矩阵中位于第3行第4列的元素值
cout << mtx(3, 4) << endl ;
system("Pause") ;
return 0 ;
}
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#include <iostream>
using
namespace
std;
class
Matrix
{
public
:
Matrix(
int
,
int
) ;
int
& operator()(
int
,
int
) ;
// 重载圆括号运算符"()"
private
:
int
* m_nMatrix ;
int
m_nRow, m_nCol ;
};
Matrix::Matrix(
int
nRow,
int
nCol)
{
m_nRow = nRow ;
m_nCol = nCol ;
m_nMatrix =
new
int
[nRow * nCol] ;
for
(
int
i = 0 ; i < nRow * nCol ; ++i)
{
*(m_nMatrix + i) = i ;
}
}
|
1
2
3
4
|
int
& Matrix::operator()(
int
nRow,
int
nCol)
{
return
*(m_nMatrix + nRow * m_nCol + nCol) ;
//返回矩阵中第nRow行第nCol列的值
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
int
main()
{
Matrix mtx(10, 10) ;
//生成一个矩阵对象aM
cout << mtx(3, 4) << endl ;
//输出矩阵中位于第3行第4列的元素值
mtx(3, 4) = 35 ;
//改变矩阵中位于第3行第4列的元素值
cout << mtx(3, 4) << endl ;
system
(
"Pause"
) ;
return
0 ;
}
|