C++复数矩阵类,内存有关问题,求教
C++复数矩阵类,内存问题,求教
#include "iostream"
#include "fstream"
using namespace std;
class complex
{
double real,imag;
public:
complex(double r){real=r;imag=0;}//只给实部赋值的构造函数
complex(double r=0,double i=0){real=r;imag=i;}//同时给实、虚部赋值的函数
double displayreal(){return real;}//返回复数实部
double displayimag(){return imag;}//返回复数虚部
};
complex co (0,0);
class CMatrix
{
private:
int x;
int y;
int z;
public:
complex ***fValue;
CMatrix(int x,int y,int z);
};
CMatrix::CMatrix(int x,int y,int z)
{
this->x=x;
this->y=y;
this->z=z;
complex ***fValue;
fValue= (complex ***)malloc((x+1) * sizeof(complex**));
if(fValue== NULL)
{
printf("Malloc False");
}
for(int i =0; i< x+1; i++)
{
fValue[i] = (complex **)malloc((y+1) * sizeof(complex*));
if(fValue[i] == NULL)
{
printf("Malloc False");
}
for( int j = 0; j< y+1; j++)
{
fValue[i][j]=(complex *)malloc((z+1) * sizeof(complex));
if(fValue[i][j] == NULL)
{
printf("Malloc False");
}
}
}
for(int i=0; i<x+1; i++)
{
for(int j=0; j<y+1; j++)
{
for(int k=0;k<z+1;k++)
{
fValue[i][j][k]=co;
}
}
}
}
void main()
{
complex cl (1,0);
CMatrix a(2,2,2);
cout<<a.fValue[1][1][0].displayreal();
}
编译无措,运行的时候显示内存冲突了。不知为何,求指教。
------解决方案--------------------
#include "iostream"
#include "fstream"
using namespace std;
class complex
{
double real,imag;
public:
complex(double r){real=r;imag=0;}//只给实部赋值的构造函数
complex(double r=0,double i=0){real=r;imag=i;}//同时给实、虚部赋值的函数
double displayreal(){return real;}//返回复数实部
double displayimag(){return imag;}//返回复数虚部
};
complex co (0,0);
class CMatrix
{
private:
int x;
int y;
int z;
public:
complex ***fValue;
CMatrix(int x,int y,int z);
};
CMatrix::CMatrix(int x,int y,int z)
{
this->x=x;
this->y=y;
this->z=z;
complex ***fValue;
fValue= (complex ***)malloc((x+1) * sizeof(complex**));
if(fValue== NULL)
{
printf("Malloc False");
}
for(int i =0; i< x+1; i++)
{
fValue[i] = (complex **)malloc((y+1) * sizeof(complex*));
if(fValue[i] == NULL)
{
printf("Malloc False");
}
for( int j = 0; j< y+1; j++)
{
fValue[i][j]=(complex *)malloc((z+1) * sizeof(complex));
if(fValue[i][j] == NULL)
{
printf("Malloc False");
}
}
}
for(int i=0; i<x+1; i++)
{
for(int j=0; j<y+1; j++)
{
for(int k=0;k<z+1;k++)
{
fValue[i][j][k]=co;
}
}
}
}
void main()
{
complex cl (1,0);
CMatrix a(2,2,2);
cout<<a.fValue[1][1][0].displayreal();
}
编译无措,运行的时候显示内存冲突了。不知为何,求指教。
class
动态数组
------解决方案--------------------
this->x=x;
this->y=y;
this->z=z;
//complex ***fValue;//这句注释,还有记着free