我在将对象 2d [5][5]
数组分配给对象时遇到问题。
这是我的数组定义
class PrintRectangle : public QWidget
{
public:
bool clicked[5][5] = {};
teacher *tech;
perceptron *p;
};
和片段感知器
类
class perceptron
{
public:
perceptron& operator=(const perceptron&);
};
当我尝试将对象分配给我的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);
}
我得到一个错误
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();
^
我只有
perceptron& perceptron::operator=(const perceptron&){
return * this;
}
在我的感知器类(class)中。我该如何纠正这个问题?我不太清楚指针。
最佳答案
*p = new perceptron[5][5];
错误的原因如下。
类型不匹配。
*p
的类型是perceptron
。
new perceptron[5][5];
的类型是perception (*)[5]
。没有从
perception (*)[5]
到perceptron
的转换。取消引用
p
。取消引用
p
,即*p
只有在为p
分配内存后才会在运行时有效。
解决方案:
您可以修复内存分配和类型不匹配问题,但我强烈建议使用标准库中的容器。
class PrintRectangle : public QWidget
{
public:
std::vector<teacher> tech; // 1D array
std::vector<std::vector<perceptron>> p; // 2D array.
};
您可以在构造函数中初始化它们:
PrintRectangle::PrintRectangle(QWidget *parent) :
QWidget(parent),
tech(clicked),
p(5, std::vector<perceptron>(5))
{
...
}
关于c++ - C++中的二维对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40775641/