动态分配的类对象
Dynamic allocated class object
我有一个简单的类,您可以在下面看到:
问题
- 我可以在我的
Playground
类构造函数中有这样的Playground(int aRow, int aColumn);
吗?如果YES在这种情况下,我必须如何为行和列的元素分配内存?如果否为什么 - 为什么我不能写
mPlayground[0][0] = 0
,我能做些什么呢?如果可以的话
花花公子.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 */
行动手册.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;
}
1a我可以在我的Playground类中拥有像这个Playground(int aRow,int aColumn)这样的构造函数吗;
是的,很琐碎:
class Playground {
int x, y;
Playgrown(int aX, int xY) : x(aX), y(aY) {}
};
1b如果是,那么在这种情况下,我必须如何为行和列的元素分配内存?如果否,为什么?
你根本不需要分配内存。Playground
不包含指针,因此不需要分配。
2为什么我不能写
mPlayground[0][0] = 0
,我能做些什么?如果可以的话。
因为您没有重载Playground
的赋值运算符。例如,
class Playground {
…
// Sample operator=. You'll need to implement its semantics
void operator=(int) {}
};
无法使用
new
初始化数组的成员。你也许可以做到这一点:
{
mPlayground[i] = new Playground[aColumn];
for(int x = 0; x < i; x++)
mPlayground[i][x] = Playground(3,4);
}
1)是:
Playground(int aRow, int aColumn)
{
}
2) 编辑:对不起,我以为这是一件更复杂的事情。我将把下面的答案留在这里,以备将来参考。为了能够编写mPlayground[0][0] = 0
,您需要重载
Playground& Playground::operator = ( int x );
老答案:
为了能够从Playboard
类访问Playground
对象,您可以重载()
运算符并调用:
Playground Playboard::operator()(int r, int c)
{
return mPlayground[r][c];
}
//...
Playboard p;
p(x,y);
或[]
操作员:
Playground* Playboard::operator[] (int r)
{
return mPlayground[r];
}
//...
Playboard p;
p[x][y];
相关文章:
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 销毁C++中动态分配的内存(数组对象)
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 动态分配的对象未初始化
- std::p air 会破坏其动态分配的对象吗?
- 动态分配对象中的字段-动态分配更好还是静态分配更好?C++
- 如果您为类的一个对象动态分配内存作为参数,会发生什么
- 使用私有析构函数删除动态分配的对象
- 动态分配许多 Boost::直方图对象
- 如何使用每个对象的单个构造函数参数动态分配C++对象数组?
- 将动态分配对象传递到 boost::any 构造函数中
- 将动态分配的对象添加到对象指针数组中
- 如何删除列表中的动态分配类对象<T>?
- 处理另一个类中类动态分配的对象数组
- 如何使用一些参数初始化动态分配的数组中的对象
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 如何复制或返回包含动态分配的内存的对象
- C 删除指向动态分配对象的指针