#include <new>
//...
wiersz* t = (wiersz*) calloc(m, sizeof(wiersz));
for(int i=0;i<n;i++) new(&t[i]) wiersz(n);
//...
//czyszczenie pamieci
for(int i=0;y<n;i++) t[i].~wiersz();
free(t); //czyscimy pamiec
Ale to nie jest zbyt eleganckie rozwiązanie. Lepiej byłoby użyć konstruktora domyślnego (normalne new) i w pętli zmienić rozmiar każdego wiersza na 'n'.
To cię powinno zainteresować:
#include <iostream>
#include <vector>
using namespace std;
template<class T>
class macierz
{
private:
class wiersz_base
{
public:
vector<T> dane;
wiersz_base(int rozmiar) { dane.resize(rozmiar, 0); };
wiersz_base& operator=(const wiersz_base& kopia) { dane = kopia.dane; return *this; };
};
public:
class wiersz : protected wiersz_base
{
public:
T& operator[](int index) { return dane[index]; };
const T& operator[](int index) const { return dane[index]; };
};
private:
int n;
vector<wiersz_base> wiersze;
public:
macierz() { n = 0; }
macierz(int _m, int _n): n(_n) { wiersze.resize(_m, wiersz_base(_n)); }
macierz(const macierz& kopia) { *this = kopia; };
int wysokosc() const { return wiersze.size(); };
int szerokosc() const { return n; };
wiersz& operator[](int index) { return reinterpret_cast<wiersz&>(wiersze[index]); };
const wiersz& operator[](int index) const { return reinterpret_cast<const wiersz&>(wiersze[index]); };
macierz& operator=(const macierz& kopia) { n = kopia.n; wiersze = kopia.wiersze; return *this; };
friend ostream& operator<<(ostream& ostr, const macierz& M)
{
for(int i = 0; i < M.wysokosc(); i++)
{
for(int j = 0; j < M.szerokosc(); j++)
ostr << M[i][j] << ' ';
ostr << endl;
}
return ostr;
};
};
int main()
{
macierz<int> A(2, 4);
cout << A << endl;
macierz<int> B(3, 5);
for(int i = 0; i < B.wysokosc(); i++)
for(int j = 0; j < B.szerokosc(); j++)
B[i][j] = i + j;
A = B;
cout << A;
cin.get();
return 0;
}