2013-11-13 2 views
0

На днях я пытался написать программу обработки матриц в C++. Сначала я создал матричный контейнер, который работает. Затем я попытался написать функцию для транспонирования матриц. Вот когда я попал в беду. Использование этой функции приводит к сбою моей программы.Возврат объекта из функции

struct imat //matrix of integer numbers 
{ 
friend int size(imat,int); 
protected: 
    const int nrows; const int ncols; //ncols = number of columns, nrows = number of rows 
    int* mat; //internal array that holds the data 
public: 
    imat(const int m, const int n): nrows(m), ncols(n) //constructor 
    { 
    mat = new int[m*n]; //creates an array of size nrows*ncols 
    for (int k=0; k<m*n; k++) mat[k]=0; //zeros all the elements 
    } 
    imat(const imat& src): nrows(src.nrows), ncols(src.ncols) //copy constructor 
    {for (int k=0; k<nrows*ncols; k++) mat[k]=src.mat[k];} //copies the contents of src to this matrix 
    imat& operator=(const imat& rhs) //assignment operator 
    { 
    if (nrows!=rhs.nrows||ncols!=rhs.ncols) throw(1); //lhs and rhs must have the same dimensions 
    for (int k=0; k<nrows*ncols; k++) mat[k]=rhs.mat[k]; //copies the contents of rhs to this matrix (lhs) 
    return *this; //return this matrix as output (lhs) 
    } 
    int& operator()(int i, int j) {return mat[(i-1)*ncols+(j-1)];} //A(i,j)=mat[(i-1)*ncols+(j-1)] (stores the matrix in the 1D array 'mat') 
~imat() {delete[] mat;} 
}; 

int size(imat mat, int dim) //gets matrix dimensions 
{ 
    if (dim==1) return mat.nrows; //dimension 1 is number of rows 
    if (dim==2) return mat.ncols; //dimernsion 2 is number of columns 
    return 0; //returns 0 if dimesion number is invalid 
} 

imat trans(imat A) 
{ 
    int m=size(A,1); //number of rows 
    int n=size(A,2); //numbers of columns 
    imat B(n,m); //creates an n*m matrix 
    for (int i=1; i<=m; i++) 
    for (int j=1; j<=n; j++) 
     B(j,i)=A(i,j); //sets the components of B to the components of the transpose of A 
    return B; 
} 

Я попытался следующие основные функции, но ни один из них не работает:

1)

int main() 
{ 
    imat A(2,3); 

    A(1,1)=11; 
    A(1,2)=12; 
    A(1,3)=13; 
    A(2,1)=21; 
    A(2,2)=22; 
    A(2,3)=23; 

    imat B = trans(A); 

    return 0; 
} 

2)

int main() 
{ 
    imat A(2,3); 

    A(1,1)=11; 
    A(1,2)=12; 
    A(1,3)=13; 
    A(2,1)=21; 
    A(2,2)=22; 
    A(2,3)=23; 

    imat B(3,2) 
    B = trans(A); 

    return 0; 
} 

Я думаю, что у него есть что-то делать с уничтожением объектов в конце области действия, хотя я не уверен. Пожалуйста, объясните мне на простом языке, в чем проблема, и как я могу это исправить.

+0

Вы пробовали отладку? Где он падает? – tenfour

ответ

2

Вы забыли выделить память для динамического массива в конструкторе копирования. Вы только начали назначать mat[...], хотя mat остался неинициализированным.

Смежные вопросы