Другие языки программирования и технологии

ООП в c++. Совсем недавно познакомился с деструкторами класса и решил опробовать их на двумерном динамическом массиве.

Не понимаю почему происходит ошибка, когда компилятор доходит до деструктора.

Class object
{
int h, l;
char** view = new char* [h];
public:
object(int h, int l)
{
this->h = h;
this->l = l;

for (int i = 0; i < h; i++)
view[i] = new char[l];
}

~object()
{
for (int i = 0; i < h; i++)
delete[] view[i];
delete[] view;
}
};

int main()
{
object cube(2,2);

return 0;
}
Чему по твоему равен h в строке - "char** view = new char* [h]" ?
Hasan Mehmonov
Hasan Mehmonov
12 592
Лучший ответ
Багитжан Ажбентаев Понял. Спасибо, всё заработало.
#include <iostream>
#include <iomanip>
using namespace std;
template<typename Type>
class Matrix {
public:
Matrix(size_t rows, size_t cols) : rows_(rows), cols_(cols), matrix_(nullptr) {
matrix_ = new (nothrow) Type* [rows_];
if (matrix_) {
for (auto i = 0U; i < rows_; ++i) {
matrix_[i] = new (nothrow) Type [cols_];
if (!matrix_[i]) {
for (auto j = 0U; j < i; ++j) delete[] matrix_[j];
delete[] matrix_;
matrix_ = nullptr;
break;
}
}
}
}
~Matrix() {
if (matrix_ != nullptr) {
for (auto i = 0U; i < rows_; ++i) delete[] matrix_[i];
delete[] matrix_;
matrix_ = nullptr;
}
}
void insert(Type value, size_t row_index, size_t col_index) {
if (matrix_ != nullptr && row_index < rows_ && col_index < cols_) {
matrix_[row_index][col_index] = value;
}
}
void fill_value(Type value) {
for (auto i = 0U; i < rows_; ++i) {
for (auto j = 0U; j < cols_; ++j) {
insert(value, i, j);
}
}
}
void show(streamsize tab) {
for (auto i = 0U; i < rows_; ++i) {
for (auto j = 0U; j < cols_; ++j) cout << setw(tab) << matrix_[i][j];
cout.put('\n');
}
}
private:
size_t rows_;
size_t cols_;
Type** matrix_;
};
int main() {
Matrix<int> matrix(4, 6);
matrix.fill_value(13);
matrix.show(5);
cin.get();
}
Aki Aki
Aki Aki
78 615