그래서 소멸자에서 2D sq_matrix를 삭제하려고합니다. 나는 내 코드를 넣어 .H 파일 여기.h 파일에서이 2D 배열을 소멸시키는 방법은 무엇입니까?
*** glibc detected *** ./hw1.out: free(): invalid pointer: 0x0000000000d6ccb0 ***
======= Backtrace: =========
/lib64/libc.so.6[0x31dd675f3e]
/lib64/libc.so.6[0x31dd678d8d]
./hw1.out[0x4011af]
./hw1.out[0x400f54]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x31dd61ed1d]
./hw1.out[0x400a69]
======= Memory map: ========
00400000-00402000 r-xp 00000000 fd:02 99359246
/* some memory map here */
Aborted (core dumped)
것 : 그러나, 나에게 메모리 오류를주고 내가 기본적으로 한 그래서
#ifndef SQUAREMATRIX_H
#define SQUAREMATRIX_H
#include <iostream>
using namespace std;
template<class T>
class SquareMatrix{
public:
int size;
T** sq_matrix;
SquareMatrix(int s){
size = s;
sq_matrix = new T*[size];
for(int h = 0; h < size; h++){
sq_matrix[h] = new T[size];
}
}
~SquareMatrix(){
for(int h = 0; h < size; h++){
delete[] sq_matrix[h];
}
delete[] sq_matrix;
}
void MakeEmpty(){
//PRE: n < width of sq matrix
//POST: first n columns and rows of sq_matrix is zero
}
void StoreValue(int i, int j, double val){
//PRE: i < width; j < height
//POST: sq_matrix[i][j] has a non-null value
}
void Add(SquareMatrix s){
//PRE: this.SquareMatrix and s are of the same width and height
//POST: this.SquareMatrix + s
}
void Subtract(SquareMatrix s){
//PRE: this.SquareMatrix and s are of the same width and height
//POST: this.SquareMatrix - s
}
void Copy(SquareMatrix s){
//PRE: s is an empty matrix
//POST: s is a ixi matrix identical to this.SquareMatrix
}
};
하는 것은 생성자 이외의 2 차원 배열을 생성하고 할당 생성자 내의 메모리. 그런 다음 소멸자에서 포인터를 삭제하려고했지만 여전히 오류가 발생합니다. 내 주요 방법은 다음과 같습니다.
#include <iostream>
#include "SquareMatrix.h"
using namespace std;
int main(){
int size;
int val;
cout << "Enter the width and height of the square matrix: ";
cin >> size;
SquareMatrix<int> sq1(size);
SquareMatrix<int> sq2(size);
return 0;
}
고마워요!
로 호출되는 이유는이 명확하게 C++ 인 C 태그? – GhostCat
여기에 오류가 표시되지 않습니다. http://codepad.org/VjuVRA9v. 제공하지 않은 코드가 더 있습니까? –
[규칙 3] (http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three)을 준수하지 않았습니다. 'SquareMatrix' 객체를 값으로 전달하고, 그렇게하기 위해 필요한 복사 작업을 적절하게 구현해야합니다. – PaulMcKenzie