我有简单的课程,你可以在下面看到:
Playground
类构造函数中使用Playground(int aRow, int aColumn);
如果 是 我必须如何为行元素分配内存和专栏?如果 否 为什么?mPlayground[0][0] = 0
我该怎么办?如果我当然可以。#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 */
#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;
}
答案 0 :(得分:2)
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 :(得分:1)
1)是的:
Playground(int aRow, int aColumn)
{
}
2)编辑:对不起,我认为这是一个更复杂的问题。我将在这里留下以下答案以供将来参考。为了能够写mPlayground[0][0] = 0
,您需要重载
Playground& Playground::operator = ( int x );
为了能够从Playground
类访问Playboard
个对象,您可以重载()
运算符并调用:
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];