模板数组,下标检查

#include <iostream>
using namespace std;

template 
<class T> class Array;
template 
<class T> class ArrayBody
{
    friend 
class Array<T>;
    T
* tpBody;
    
int iRows, iColumn, iCurrentRow;
    ArrayBody(
int iRsz, int iCsz)
    
{
        tpBody 
= new T[iRsz * iRsz];
        iRows 
= iRsz;
        iColumn 
= iCsz;
        iCurrentRow 
= -1;
    }

public:
    T
& operator[](int j)
    
{
        
bool row_error =false, column_error =false;
        
try
        
{
            
if(iCurrentRow < 0 || iCurrentRow >= iRows)
                row_error 
=true;
            
if(j < 0 || j >= iColumn)
                column_error 
=true;
            
if(row_error || column_error)
                
throw 'e';
        }

        
catch (char)
        
{
            
if(row_error)
                cerr 
<< "row access invalid!" << iCurrentRow << endl;
            
if(column_error)
                cerr 
<< "column access invalid!" << j << endl;
        }

        
return tpBody[iCurrentRow * iColumn + j];
    }

    
~ArrayBody()
    
{delete[] tpBody;}
}
;
template 
<class T> class Array
{
    ArrayBody
<T> tBody;
public:
    ArrayBody
<T>& operator[](int i)
    
{
        tBody.iCurrentRow 
= i;
        
return tBody;
    }

    Array(
int iRsz, int iCsz): tBody(iRsz, iCsz){}
}
;
 
#include "t1.h"

void main()
{
    Array
<int> a1(10,20);
    Array
<double> a2(3,5);
    
int b1;
    
double b2;
    b1 
= a1[-5][10];
    b1 
= a1[10][15];
    b1 
= a1[1][4];
    b2 
= a2[2][6];
    b2 
= a2[10][20];
    b2 
= a2[1][4];
    getchar();
}
此题要求当访问二位数组元素时,通过定义类,判断行下标及列下标越界与否。如果不看程序,可能会认为由于是二维数组,那么要用到两次运算符[ ]重载。但是如何在一个类中实现两次同一个运算符的重载呢?这样做似乎不太方便,那么应该想到定义两个类,当第一个类调用重载的操作符时,使此函数返回第二个类的对象,在第二个类中,同样定义了运算符[ ]重载。但在第一个类中的重载操作符要能访问第二个类的私有成员,那么就应该把第一个类声明为第二个类的友元。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值