Per completezza, posto la soluzione che usa la classe:
Codice PHP:
#include <iostream>
using namespace std;
template <class T>
class Mat {
private:
int n;
int m;
T** mat;
public:
Mat(int p_n, int p_m);
~Mat();
int get_n();
int get_m();
T& operator() (int row, int col);
T operator() (int row, int col) const;
void init();
};
template <class T>
Mat<T>::Mat(int p_n, int p_m) {
n = p_n;
m = p_m;
mat = new T*[n];
for(int i=0;i<n;i++) {
mat[i] = new T[m];
}
}
template <class T>
Mat<T>::~Mat() {
for(int i=0;i<n;i++) {
delete(mat[i]);
}
delete(mat);
}
template <class T>
int
Mat<T>::get_n() {
return n;
}
template <class T>
int
Mat<T>::get_m() {
return m;
}
template <class T>
T& Mat<T>::operator() (int row, int col) {
if(row >= n || col >= m)
throw "Out of range";
return mat[row][col];
}
template <class T>
T Mat<T>::operator() (int row, int col) const {
if(row >= n || col >= m)
throw "Out of range";
return mat[row][col];
}
template <class T>
void Mat<T>::init() {
for(int i=0; i<n;i++) {
for(int j=0;j<m;j++) {
mat[i][j] = i*j;
}
}
}
template <class T>
void stampa(Mat<T> mat) {
for(int i=0;i<mat.get_n();i++) {
for(int j=0;j<mat.get_m();j++) {
cout << mat(i,j) << " | ";
}
cout << "\n";
}
}
int main() {
Mat<double> mat = Mat<double>(3,4);
mat.init();
stampa(mat);
}