Reputation: 10755
I have simple class which you can see below:
Playground
class constructor like this Playground(int aRow, int aColumn);
If YES how I must allocate memory in then case for elements of row and column ? If NO why ?mPlayground[0][0] = 0
and what can I do to do that ? If I can of course.#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;
}
Upvotes: 0
Views: 2045
Reputation: 168876
1a Can I have in my Playground class constructor like this Playground(int aRow, int aColumn);
Yes, trivially:
class Playground {
int x, y;
Playgrown(int aX, int xY) : x(aX), y(aY) {}
};
1b If YES how I must allocate memory in then case for elements of row and column ? If NO why ?
You don't have to allocate memory at all. Playground
contains no pointers, and consequently requires no allocation.
2 Why I can't write
mPlayground[0][0] = 0
and what can I do to do that ? If I can of course.
Because you haven't overloaded the assignment operator for Playground
. For example,
class Playground {
…
// Sample operator=. You'll need to implement its semantics
void operator=(int) {}
};
new
. You might be able to do this:
{
mPlayground[i] = new Playground[aColumn];
for(int x = 0; x < i; x++)
mPlayground[i][x] = Playground(3,4);
}
Upvotes: 2
Reputation: 258678
1) Yes:
Playground(int aRow, int aColumn)
{
}
2) EDIT: Sorry I thought it was a more complicated matter. I'll leave the below answer here for future reference. To be able to write mPlayground[0][0] = 0
, you'll need to overload
Playground& Playground::operator = ( int x );
To be able to access Playground
objects from the Playboard
class, you can overload the ()
operator and call:
Playground Playboard::operator()(int r, int c)
{
return mPlayground[r][c];
}
//...
Playboard p;
p(x,y);
or the []
operator:
Playground* Playboard::operator[] (int r)
{
return mPlayground[r];
}
//...
Playboard p;
p[x][y];
Upvotes: 1