【发布时间】:2015-04-21 01:18:31
【问题描述】:
我在 c++ 和其他面向对象语言方面相对较新(我已经完成了一个学期的 C 课程,现在我正在学习 c++ 课程)。我在通过与同学的班级制作动态分配的二维数组时遇到问题。
练习本身是:
准备一个名为“矩阵”的类,能够存储二维 动态分配的数组(对于浮点变量)。请记住 高度和宽度等信息必须正确存储 在某处,元素指针也是如此。
该类需要包含允许创建 使用以下策略之一的对象: 由 MxN 个元素组成的数组,例如:
Array A (4, 5);空数组的创建:
Array B; The creation of an array that is a copy of another previous one: Array C (A);
经过一段时间试图找出它无法正常工作的原因后,我们的代码目前是这样的: obs:“Matriz”是我们语言中二维数组的称呼。
Matriz.h
#pragma once
class Matriz{
public:
int l, c;
float** matriz;
void setL(int _l);
void setC(int _c);
int getL();
int getC();
Matriz();
Matriz(int _l, int _c);
Matriz(Matriz& m);
float **getMatriz();
float getElement(int pL, int pC);
void setElement(int pL, int pC, float value);
};
Matriz.cpp
#include "Matriz.h"
Matriz::Matriz(){
l = c = 0;
matriz = new float*[l];
for (int i = 0; i<l; i++) {
matriz[l] = new float[c];
}
}
Matriz::Matriz(Matriz& m){
l = m.getL();
c = m.getC();
matriz = new float*[l];
for (int i = 0; i<l; i++) {
matriz[l] = new float[c];
}
for (int i = 0; i<l; i++) {
for (int j = 0; j<l; j++) {
matriz[i][j] = m.matriz[i][j];
}
}
}
Matriz::Matriz(int _l, int _c){
l = _l;
c = _c;
matriz = new float*[l];
for (int i = 0; i<l; i++) {
matriz[l] = new float[c];
}
}
float **Matriz::getMatriz(){
return matriz;
}
int Matriz::getC(){
return c;
}
int Matriz::getL(){
return l;
}
void Matriz::setC(int _c){
c = _c;
}
void Matriz::setL(int _l){
l = _l;
}
float Matriz::getElement(int pL, int pC){
return matriz[pL][pC];
}
void Matriz::setElement(int pL, int pC, float value){
matriz[pL][pC] = value;
}
main.cpp
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int l = 2, c = 2;
float **m;
m = new float*[l];
for (int i=0; i<2; i++) {
m[i] = new float[c];
}
Matriz a(2, 2);
a.setC(2);
a.setL(2);
cout << " c = " << a.getC() << " l= " << a.getL() << "\n";
for (int i = 0; i<l; i++) {
for (int j = 0; j<c; j++) {
a.setElement(i, j, 0);
cout << " Elemento " << 1 << " " << 1 << " = " << a.getElement(l, c) << "\n";
}
}
a.setElement(0, 0, 1); // <- this is just for testing
system("pause");
}
iostream 和类头都包含在 stdafx.h 中
在 MSVS 2013 上编译它在
void Matriz::setElement(int pL, int pC, float value){
matriz[pL][pC] = value;
}
我们不确定为什么,调试器给了我 “ConsoleApplication15.exe 中 0x01092E27 处未处理的异常:0xC0000005:访问冲突写入位置 0xCDCDCDD1。”
然而,我们怀疑数组有问题,当程序尝试将某些内容写入其中的元素时,它根本不存在/无法访问,因此无法更改该元素的值特定元素。
我们感谢您提供的任何帮助或建议,随时提出改进或编码建议,学习新事物总是好的 =)。
【问题讨论】:
-
Matriz 构造函数中的 for 循环正在引用 matriz[l],而我认为它应该引用 matriz[i]
-
赋值运算符?破坏者?他们在哪?此外,
main()中的那些初始行应该完成什么?你分配内存,然后......你什么都不做。分配内存意味着你有责任正确地释放它,否则你就会有内存泄漏。 -
setC和setL未正确实现;如果他们改变了大小,那么你将需要改变分配的内存量。 -
为什么不简单地使用
std::vector<std::vector<float>>或类似的东西? -
我目前正在尝试联系负责这部分代码的同事 PaulMcKenzie,我会尽快让他回答。据我所知,他在 main 开头添加程序之前提到该程序已中断,但我认为问题出在其他地方,他认为这是巧合的“修复”。一旦我让它工作,我就会从析构函数开始,非常感谢你的输入!! =)
标签: c++ arrays dynamic-allocation