【发布时间】:2012-03-07 21:49:05
【问题描述】:
我有一个简单的类,你可以在下面看到:
问题
- 我可以在我的
Playground类构造函数中有这样的Playground(int aRow, int aColumn);如果YES 在这种情况下我必须如何为行和列的元素分配内存?如果否为什么? - 为什么我不能写
mPlayground[0][0] = 0,我该怎么做?如果可以的话。
Playboard.h
#pragma once
#ifndef PLAYBOARD_H
#define PLAYBOARD_H
class Playground
{
public:
Playground()
{
}
};
class Playboard
{
public:
Playboard();
~Playboard();
private:
Playground** mPlayground;
int mRows;
int mColumns;
public:
void Initialize(int aRow, int aColumn);
};
#endif /** PLAYBOARD_H */
Playboard.cpp
#include "Playboard.h"
Playboard::Playboard()
{
mPlayground = 0;
}
void Playboard::Initialize(int aRow, int aColumn)
{
// Set rows and columns in order to use them in future.
mRows = aRow;
mColumns = aColumn;
// Memory allocated for elements of rows.
mPlayground = new Playground*[aRow];
// Memory allocated for elements of each column.
for (int i=0; i<aRow; i++)
mPlayground[i] = new Playground[aColumn];
}
Playboard::~Playboard()
{
// Free the allocated memory
for (int i=0; i<mRows; i++)
delete[] mPlayground[i];
delete[] mPlayground;
}
【问题讨论】:
-
您是否在编译器中尝试过您的代码?我看不出它有什么问题。
-
你可以,但你不应该使用
new。如果这样做,如果其中一个分配失败,您将泄漏内存。我们通常在 C++ 中将std::vector用于数组。 -
@BenRussell 你读过问题了吗?
-
@LuchianGrigore 我认为他没有
-
@avakar 我知道
std::vector,但我不想使用它。我想在不使用 stl 库的情况下编写我的课程。
标签: c++ class memory-management dynamic