gpt4 book ai didi

c++ - 进程退出,返回值 3221226356

转载 作者:太空宇宙 更新时间:2023-11-04 11:24:56 25 4
gpt4 key购买 nike

我开始为矩阵操作编写简单的类,一个构造函数用一个数字填充矩阵,另一个构造函数以二维数组作为参数。

    #include <iostream>

using namespace std;
int i,j;
class Matrica
{
public:
Matrica(int, int, double);
Matrica(int, int, double*);
~Matrica();
void saberi(Matrica, Matrica);
void read();
void print();
private:
int n,m;
double* matrix;
};

Matrica::Matrica(int a, int b, double broj)
{
n = a;
m = b;
matrix = new double[n*m];
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
matrix[i*n + j] = broj;
}
}
}

Matrica::Matrica(int a, int b, double* matr)
{
n = a;
m = b;
matrix = new double[n*m];
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
matrix[i*n + j] = matr[i*n +j];
}
}

}
Matrica::~Matrica() {
delete[] matrix;
}

void Matrica::read() {
double e;
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
cout<< "insert element ["<<i<<"]["<<j<<"] :" <<endl;
cin >> e;
matrix[n*i +j] = e;
cout<< endl;
}
}
}

void Matrica::print() {
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
cout << matrix[n*i + j] << " ";
}
cout << endl;
}
}
void Matrica::saberi(Matrica A, Matrica B) {
cout << "foo";
}

int main()
{

Matrica A(3,3,1);
double K[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
Matrica B(3,3,&K[0][0]);
Matrica C(3,3,7);
C.saberi(A,B);
return 0;
}

在我添加以两个对象作为参数的空“saberi”方法之前,我的程序运行正常。如果我调用它,我的程序会崩溃并返回 3221226356 值。有什么问题吗?提前致谢。

最佳答案

因为你已经定义了你的函数签名

void saberi(Matrica, Matrica);

那里的 Matrica 对象是按值传递的,但是您没有为 Matrica 类提供合适的复制构造函数。

解决您当前问题的最简单方法是通过引用传递参数

void saberi(Matrica&, Matrica&);

void saberi(const Matrica&, const Matrica&);

无论如何,从长远来看,您应该提供一个适当的复制构造函数

Matrica(const Matrica&);

或禁止它(只需将声明放在类的 private 部分)。

关于c++ - 进程退出,返回值 3221226356,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27020985/

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