动态分配的类对象

Dynamic allocated class object

本文关键字:对象 动态分配      更新时间:2023-10-16

我有一个简单的类,您可以在下面看到:

问题

  1. 我可以在我的Playground类构造函数中有这样的Playground(int aRow, int aColumn);吗?如果YES在这种情况下,我必须如何为行和列的元素分配内存?如果为什么
  2. 为什么我不能写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];