您的位置:首页 > 编程语言 > C语言/C++

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

2017-03-24 20:05 609 查看
重载数组下标运算符"[]":#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 ;
}


11121314151617181920212223242526
#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 ;
    
}
}
重载圆括号运算符"()":
1234
int
& Matrix::operator()(
int
 
nRow, 
int
 
nCol)
{
    
return
 
*(m_nMatrix + nRow * m_nCol + nCol) ; 
//返回矩阵中第nRow行第nCol列的值
}
测试代码:
12345678910111213
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 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: