gpt4 book ai didi

c++ - 从函数返回对象

转载 作者:行者123 更新时间:2023-11-28 03:05:00 24 4
gpt4 key购买 nike

前几天,我试图用 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;
}

我的猜测是它与函数范围末尾的对象销毁有关,但我不确定。请用简单的语言向我解释问题是什么以及我该如何解决。

最佳答案

您忘记在复制构造函数中为动态数组分配内存。您刚刚开始分配给 mat[...],即使 mat 未初始化。

关于c++ - 从函数返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19959003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com