我在使用 Complex() 的基类填充常规二维数组时遇到了问题。我在派生类 matrix() 的构造函数中初始化了数组,我确保我正确地填充了它,但无论我做什么,我都会收到错误消息。我不断收到访问冲突写入位置,这可能意味着数组未正确初始化,我正在写入的数据改为写入 CPU。这是我的 Matrix.h 文件
#pragma
#ifndef MATRIX_H
#define MATRIX_H
#include "Complex.h"
#include "stdafx.h"
#include <iostream>
using namespace std;
class Matrix : public Complex
{
private:
Complex **a;
double real;
double imag;
double length, width;
public:
Matrix(): real( 0.0 ), imag( 0.0 ) {}
void setMatrix(int b , int c) {
int i, j;
a=new Complex*();
length=b, width=c;
for(int k=0;k<b;k++)
for(int p=0; p<c; p++)
a[k]=new Complex();
for (i = 0; i <= b; i++)
for (j = 0; j<= c; j++)
a[i][j].setImag(rand() % 100);
a[i][j].setReal(rand() % 100);
}
Matrix add( const Matrix & ) const;
void print() const;
void setMatrix(int b, int c) const;
};
#endif
这是我的 Matrix.cpp 文件
#include <iostream>
using namespace std;
#include "Matrix.h"
Matrix Matrix::add( const Matrix &c ) const
{
Matrix result;
result.setMatrix(2,2);
int i,j;
for(i=0; i<c.length; i++) {
for(j=0; j<c.width;j++) {
result.a[i][j].setImag(a[i][j].getImag() + c.a[i][j].getImag());
result.a[i][j].setReal(a[i][j].getReal() + c.a[i][j].getReal());
}
}
return result;
}
void Matrix::print() const {
for(int i=0; i<length; i++) {
for(int j=0; j<width; j++) {
cout << "(" << a[i][j].getReal() << "," << a[i][j].getImag() << ")/n";
}
}
}
任何帮助将不胜感激!
最佳答案
我什至不打算尝试修复这段代码的所有错误,所以你会遇到更多问题,但就内存分配而言
a=new Complex*();
只分配一个复合体,所以只有a[0]
有效。这必须替换为
a=new Complex*[length];
同样的道理
a[k]=new Complex();
必须替换为
a[k]=new Complex[width];
所以 setMatrix
中的分配变为:
void setMatrix(int b , int c)
{
length=b;
width=c;
a=new Complex*[length];
for(int k=0;k<length;k++)
{
a[k]=new Complex[width];
}
}
注意事项:
- 不要在 header 中使用
using namespace std
。 - 不喜欢使用
using namespace std
- 如果你使用原始指针,你需要一个析构函数
- 打印不应该是 Matrix 的一部分
- 矩阵应概率。不是从 Complex 派生的 ...
关于c++ - 制作一个充满基础 Complex 类的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666095/