lukassz lukassz - 16 days ago 5
C++ Question

2D array of object in C++

I have a problem with assign object 2d

[5][5]
array to object.

This is my array definition

class PrintRectangle : public QWidget
{

public:
bool clicked[5][5] = {};
teacher *tech;
perceptron *p;

};


And fragment
perceptron
class

class perceptron
{
public:
perceptron& operator=(const perceptron&);
};


When I try to assign object to my
perceptron *p


PrintRectangle::PrintRectangle(QWidget *parent) : QWidget(parent)
{
tech = new teacher(clicked);

*p = new perceptron[5][5];

for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
p[i][j] = new perceptron();
p[i][j].randweight();
}
}

double learnConst = 0.1;
tech->learnPerceptrons(p);
}


I get an error

E:\Sieci Neuronowe\Perceptron\printrectangle.cpp:10: error: no match for 'operator=' (operand types are 'perceptron' and 'perceptron (*)[5]')
*p = new perceptron[5][5];
^

E:\Sieci Neuronowe\Perceptron\printrectangle.cpp:16: error: no match for 'operator[]' (operand types are 'perceptron' and 'int')
p[i][j] = new perceptron();
^


I have only

perceptron& perceptron::operator=(const perceptron&){

return * this;
}


In my perceptron class. How can I correct this? I don't cleary understend pointers.

Answer
*p = new perceptron[5][5];

is wrong for the following reasons.

  1. Type mismatch.

    Type of *p is perceptron.
    Type of new perceptron[5][5]; is perception (*)[5].

    There is no conversion from perception (*)[5] to perceptron.

  2. Dereferencing p.

    Dereferencng p, i.e. *p is going to be valid at run time only after you have allocated memory for p.


Solution:

You can fix your memory allocation and type mismatch problems but I strongly recommend using containers from the standard library.

class PrintRectangle : public QWidget
{
  public:

    std::vector<teacher> tech;               // 1D array
    std::vector<std::vector<perceptron>> p;  // 2D array.
};

You can initialize them in the constructor with:

PrintRectangle::PrintRectangle(QWidget *parent) :
   QWidget(parent),
   tech(clicked),
   p(5, std::vector<perceptron>(5))
{
   ...
}