注册 登录
编程论坛 C++教室

[求助]郁闷了好几天的程序!

轮廓 发布于 2007-07-19 13:17, 918 次点击

//编译成功,连接也成功,但执行时出现内存错误,不懂?

#include<iostream.h>
#include<stdlib.h>
//using namespace std;
class Matrix //矩阵类
{

private:
int rows,cols; //矩阵的行列
double *m; //矩阵存放的元素,按行存放

public:
Matrix(int N_rows=2,int M_cols=2);
~Matrix();

MatriX(const Matrix &ZM);

Matrix operator+(Matrix &AMD); //重载+
void input();//矩阵输入
void display();//矩阵输出
};


Matrix::Matrix(int N_rows,int M_cols)
{
rows=N_rows;
cols=M_cols;

m = new double [rows * cols];

}


Matrix::~Matrix()
{
delete []m;
}

Matrix::MatriX(const Matrix &ZM)
{


int r=0;

for(int Row=1;Row<=rows;Row++)
for(int Col=1;Col<=cols;Col++)

m[r++]=ZM.m[r++];



}


Matrix Matrix::operator+(Matrix &AMD)
{
int r=0;

if(rows==AMD.rows && cols==AMD.cols)
{
Matrix GM(rows,cols);

for(int Row=1;Row<=rows;Row++)
for(int Col=1;Col<=cols;Col++)
{
GM.m[r++]=m[r++]+AMD.m[r++];
}




return GM;
}

else
{
cout<<"距阵相加运算错误"<<endl;
exit(0);



}

}



void Matrix::input()
{
int r=0;
for(int Row=1;Row<=rows;Row++)
for(int Col=1;Col<=cols;Col++)
cin>>m[r++];

}


void Matrix::display()
{
int r=0;
for(int Row=1;Row<=rows;Row++)
{
for(int Col=1;Col<=cols;Col++)
cout<<m[r++]<<'\t';

cout<<endl;
}

}

int main()
{

Matrix a(2,2); //矩阵a 2行2列
Matrix b(2,2); //矩阵b 2行2列
Matrix c(2,2); //矩阵c 2行2列


cout<<"请输入你想要的2行2列的距阵:\t\n";
a.input();


cout<<"请输入你想要的2行2列的距阵:\t\n";
b.input();
cout<<endl;

c=a+b;
cout<<"下面是你想得到的相加后的2行2列的距阵:\t\n\n";
c.display();

return 0;

}

11 回复
#2
轮廓2007-07-19 13:23

斑竹、各位大虾help me

#3
leeco2007-07-19 13:26
自己调试啊,多数是wild pointer的问题咯
#4
轮廓2007-07-19 13:32
自己调试了,就是在DOS界面里会出现一个有 终止,重试,取消 的界面,无论也不会有结果,不懂
#5
轮廓2007-07-19 13:38

谢谢啊,在帮我看看吧!

#6
轮廓2007-07-19 13:43
[IMG]http://C:\Documents and Settings\Administrator\桌面[/IMG]
#7
轮廓2007-07-20 10:38

昨天又调试了,原来是析构函数的问题,单不知道为什么

#8
一番宝瓶2007-07-20 12:26
如果你有用new在堆区分配空间,析构函数里必须用delete来释放
#9
HCL2007-07-20 14:48

好像重载操作符有问题!

#10
smithallen2007-07-20 14:49
问题出在c=a+b上了,因为你的类中含有指向动态分配内存的指针成员,在复制此成员时就可能出现危险。
#11
轮廓2007-07-22 02:38
谢谢几位,我是说程序已经能正常执行了,只需要把析构函数去掉,但不知道Why..........?
#12
jianvsgao2007-07-22 17:00

头文件不能那么写
#include"iostrema.h"
#include"stdlib.h"

如果是core C++ 的话,那标准库文件应该:
#include<iostream>
#include<stdlib>

1