C++之重载数组下标[]与圆括号()运算符的方法

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

#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 ;
}
  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值