#include<iostream>
#include<cmath>
using namespace std;
class macierz
{
public:
macierz(const macierz& m); //konstruktor kopiujacy
macierz(int x, int y);
~macierz();
void wypelnij();
int &x() {return _x;}
int &y() {return _y;}
const int &x() const {return _x;}
const int &y() const {return _y;}
friend ostream & operator<< (ostream &out, const macierz &m);
friend macierz operator+(macierz& m1, macierz& m2); // jesli funkcja ma miec dostep do prywatnej skladowej mac, to musi byc zaprzyjazniona
private:
int _x; //Wysokosc
int _y; //Szerokosc
double** mac;
};//:}
void macierz::wypelnij()
{
if(mac)
{
double w;
for(int i=0;i<_x;++i)
{
for(int j=0;j<_y;++j)
{
cout<<"Wiersz "<< i <<" Kolumna " <<j<<" \n";
cin>>w;
mac[i][j]=w;
}
}
cout<<"Macierz wypelniona\n";
}
}
macierz::macierz(const macierz& m)
{
macierz nowa(m._x,m._y);
for(int i=0;i<m._x;i++)
{
for(int j=0;j<m._y;j++)
{
nowa.mac[i][j]=m.mac[i][j];
}
}
cout << nowa;
}
macierz::macierz(int x, int y): _x(x), _y(y)
{
mac = new double* [_x];
if(!mac)
{
cerr<< "Memory Ivalid";
}
for(int i=0;i<_x;++i)
{
mac[i] = new double[_y];
if(!mac[i])
cerr<< "Memory Ivalid";
}
for(int i=0;i<_x;++i)
{
for(int j=0;j<_y;++j)
{
mac[i][j] =0;
}
}
}
ostream & operator<< (ostream &out, const macierz &m)
{
for(int i=0;i<m._x;i++)
{
for(int j=0;j<m._y;j++)
{
out<<m.mac[i][j]<<" ";
}
out<<"\n";
}
return out;
}
macierz operator+ (macierz &m1,macierz &m2)
{
if(m1.x() == m2.x() && m1.y() == m2.y())
{
macierz m3(m1.x(),m2.y());
for(int i=0;i<m1.x();++i)
{
for(int j=0;j<m1.y();++j)
{
m3.mac[i][j]=m1.mac[i][j]+m2.mac[i][j];
}
}
return m3;
}
else
cout<<"Macierze musza posiadac taki sam rozmiar";
}
macierz::~macierz()
{
for(int i=0;i<_x;++i)
delete [] mac[i];
delete [] mac;
}
int main()
{
macierz A(2,2), B(2,2);
A.wypelnij();
B.wypelnij();
cout<<A<<"\n";
cout<<B<<"\n";
cout<<A+B;
cin.get();
system("PAUSE");
return 0;
}
Przy próbie dodawania macierzy, program się zawiesza. Co moze być tego powodem ?
Czy istnieje możliwość zmiany konstruktora kopiującego w taki sposób by można było zmieniać wartości macierzy m3 ??