matrix知识介绍
namespace mylib {
template<typename Ty,
const size_t line_sz,
const size_t row_sz>
class matrix {
public:
//typedef
typedef Ty value_type;
typedef size_t size_type;
typedef ptrdiff_t diffecence_type;
typedef Ty* pointer;
typedef const Ty* const_pointer;
typedef Ty& reference;
typedef const Ty& const_reference;
typedef Ty(*cmat_ptr)[row_sz];
typedef const Ty(*const_cmat_ptr)[row_sz];
//constructors
matrix(void)
: mat_ptr(NULL)
{
get_memory();
for(size_type i = 0; i < line_sz; ++i)
for(size_type j = 0; j < row_sz; ++j)
mat_ptr[i][j] = value_type();
}
matrix(const_cmat_ptr cmat)
: mat_ptr(NULL)
{
get_memory();
for(size_type i = 0; i < line_sz; ++i)
for(size_type j = 0; j < row_sz; ++j)
mat_ptr[i][j] = cmat[i][j];
}
matrix(const matrix<Ty,line_sz,row_sz>& mat)
: mat_ptr(NULL)
{
get_memory();
for(size_type i = 0; i < line_sz; ++i)
for(size_type j = 0; j < row_sz; ++j)
mat_ptr[i][j] = mat[i][j];
}
//destructors
~matrix(void)
{
destroy_memory();
}
//public member methods
const size_type line_size(void) const
{
return line_sz;
}
const size_type row_size(void) const
{
return row_sz;
}
const size_type size(void) const
{
return size_type(line_sz * row_sz);
}
//operator member
matrix<Ty,line_sz,row_sz>&
operator= (const matrix<Ty,line_sz,row_sz>& mat)
{
if(this == &mat)
return *this;
if(mat_ptr != BULL)
destroy_memory();
get_memory();
for(size_type i = 0; i < line_sz; ++i)
for(size_type j = 0; j < row_sz; ++j)
mat_ptr[i][j] = mat[i][j];
}
matrix<Ty,line_sz,row_sz>&
operator= (const_cmat_ptr cmat)
{
if(this == cmat)
return *this;
if(mat_ptr != BUL L)
destroy_memory();
get_memory();
for(size_type i = 0; i < line_sz; ++i)
for(size_type j = 0; j < row_sz; ++j)
mat_ptr[i][j] = cmat[i][j];
}
pointer operator[] (const size_type lidx)
{
if(lidx >= line_sz)
{
std::cerr << "lidx >= line_sz" << std::endl;
std::exit(EXIT_FAILURE);
}
return mat_ptr[lidx];
}
const_pointer operator[] (const size_type lidx) const
{
if(lidx >= line_sz)
{
std::cerr << "lidx >= line_sz" << std::endl;
std::exit(EXIT_FAILURE);
}
return mat_ptr[lidx];
}
operator const_cmat_ptr() const
{
return mat_ptr;
}
private:
//private methods
void get_memory(void)
{
mat_ptr = new value_type[line_sz][row_sz];
}
void destroy_memory(void)
{
delete [] mat_ptr;
}
//date member
cmat_ptr mat_ptr;
};
}
本文地址:http://www.45fan.com/a/question/70581.html