operator override of a Matrix class

Copy from FAQS:

Use operator() rather than operator[].
  When you have multiple subscripts, the cleanest way to do it is with operator() rather than
with operator[]. The reason is that operator[] always takes exactly one parameter, but
operator() can take any number of parameters (in the case of a rectangular matrix, two
parameters are needed). 


class  Matrix {
public :
    Matrix(unsigned rows, unsigned cols);
    
double &   operator
        () (unsigned row, unsigned col); ¬ subscript operators often come 
in  pairs
        
double   operator
        () (unsigned row, unsigned col) 
const ; ¬ subscript operators often come  in  pairs
        ...
        
~ Matrix();  //  Destructor
    Matrix( const  Matrix &  m);  //  Copy constructor
    Matrix &   operator =  ( const  Matrix &  m);  //  Assignment operator
    ...
private :
    unsigned rows_, cols_;
    
double *  data_;
};
inline
Matrix::Matrix(unsigned rows, unsigned cols)
: rows_ (rows)
, cols_ (cols)
// data_ <--initialized below (after the 'if/throw' statement)
{
    
if  (rows  ==   0   ||  cols  ==   0 )
        
throw  BadIndex( " Matrix constructor has 0 size " );
    data_ 
=   new   double [rows  *  cols];
}
inline
Matrix::
~ Matrix()
http:
// www.parashift.com/c++-faq-lite/operator-overloading.html (10 of 22)2007-7-31 12:10:35
[ 13 ] Operator overloading Updated !  , C ++  FAQ Lite
{
    delete[] data_;
}
inline
double &  Matrix:: operator () (unsigned row, unsigned col)
{
    
if  (row  >=  rows_  ||  col  >=  cols_)
        
throw  BadIndex( " Matrix subscript out of bounds " );
    
return  data_[cols_ * row  +  col];
}
inline
double  Matrix:: operator () (unsigned row, unsigned col)  const
{
    
if  (row  >=  rows_  ||  col  >=  cols_)
        
throw  BadIndex( " const Matrix subscript out of bounds " );
    
return  data_[cols_ * row  +  col];
}

Then you can access an element of Matrix m 
using  m(i,j) rather than m[i][j]:

int  main()
{
    Matrix m(
10 , 10 );
    m(
5 , 8 =   106.15 ;
    std::cout 
<<  m( 5 , 8 );
    ...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值