分享

C++之重载数组下标[]与圆括号()运算符的方法 – 春风细雨's Blog

 Null872 2014-12-11

    所谓运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。本文将示例如何重载数组下标"[]"与圆括号"()"运算符。

重载数组下标运算符"[]":

声明Vector类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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] ;
};
重载数组下标运算符"[]":
1
2
3
4
5
6
7
8
9
10
int& Vector::operator[](int nIndex)
{
    if (nIndex < 0 || nIndex >= 4) // 数组越界检查 
    {   
        cout << "数组下标越界!" << endl ;
        return m_nGril[0] ;
    }
    return m_nGril[nIndex];
}
测试代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 ;
}

  上述代码中定义了一个Vector类变量vt,调用vt[2]即相当于调用类函数vt.operator[](2),接下来,你懂的~

重载圆括号运算符"()":

声明Matrix类:
1
2
3
4
5
6
7
8
9
10
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 ;
}

  上述代码中定义了一个Matrix类变量mtx,调用mtx(3, 4)即相当于调用mtx.operator()(3, 4),接下来,你懂的~

转载请注明:春风细雨's Blog ? C++之重载数组下标[]与圆括号()运算符的方法

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多