Hi,
After years of C programming, I'm starting to learn C++ and am amazed at the number of keywords and how much more complex the syntax is. It is becomming clear to me that C++ is meant for big programs.
I'm writing a template matrix class as an exercise. I am modeling it on the STL vector template class. I am wondering about my use of the keywords inline, const, delete vs delete[], explicit.
In the following code have I used the words inline and const in the correct places? Should I be using delete or delete[] in my destructor? Should I be using the word explicit in any of my constructors or anywhere else?
Thanks. Happy New Year!
Peter
Code:
#include <iostream>
typedef unsigned long size_type;
template <class Type>
class Matrix {
public:
Matrix(size_type ro=0, size_type co=0);
Matrix(size_type ro, size_type co, Type val);
Matrix(const Matrix &ma);
~Matrix() {delete mat;}
size_type rows() const {return r;}
size_type cols() const {return c;}
void display() const;
protected:
void init(size_type ro, size_type co);
size_type r, c;
Type *mat;
};
template <class Type>
inline void Matrix<Type>::init(size_type ro, size_type co){
mat = new Type[ro*co];
assert (mat != 0);
r = ro;
c = co;
}
template <class Type>
inline Matrix<Type>::Matrix(size_type ro, size_type co){
init(ro,co);
}
template <class Type>
inline Matrix<Type>::Matrix(size_type ro, size_type co, Type val){
init(ro,co);
unsigned int i, j;
for (i=0; i<r; i++){
for (j=0; j<c; j++){
mat[i*c+j] = val;
}
}
}
template <class Type>
inline Matrix<Type>::Matrix(const Matrix &ma){
init(ma.r,ma.c);
unsigned int i, j;
for (i=0; i<r; i++){
for (j=0; j<c; j++){
mat[i*c+j] = ma.mat[i*c+j];
}
}
}
template <class Type>
void Matrix<Type>::display() const{
unsigned int i, j;
std::cout << "[" << std::endl;
for (i=0; i<r; i++){
std::cout << "[";
for (j=0; j<c; j++){
std::cout << mat[i*c+j];
if (j < c-1) std::cout << " ";
}
std::cout << "]" << std::endl;
}
std::cout << "]" << std::endl;
}
int main (void) {
Matrix<double> mat(2,4,-9.9);
std::cout << "mat = ";
mat.display();
std::cout << "(rows, cols) = (" << mat.rows() << ", "
<< mat.cols() << ")" << std::endl;
Matrix<double> mat2;
std::cout << "mat2 = ";
mat2.display();
std::cout << "(rows, cols) = (" << mat2.rows() << ", "
<< mat2.cols() << ")" << std::endl;
const Matrix<double> mat3 = mat;
std::cout << "mat3 = ";
mat3.display();
std::cout << "(rows, cols) = (" << mat3.rows() << ", "
<< mat3.cols() << ")" << std::endl;
return 0;
}