c++ - C++中的二维对象数组

标签 c++ arrays qt oop

我在将对象 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];

错误的原因如下。

  1. 类型不匹配。

    *p 的类型是perceptron
    new perceptron[5][5]; 的类型是 perception (*)[5]

    没有从 perception (*)[5]perceptron 的转换。

  2. 取消引用 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/

相关文章:

c++ - 在 Qt 中实现 winevent 时是否需要 WM_PAINT

c++ - 在 opencv 中应用过滤时出错

java - A* 具有敌人意识

c++ - 如何更改 tittleBar 按钮,如 Qt QWidget 中的关闭和最小化按钮

c++ - STL Sort静态函数的使用

wpf - 在 XAML 中填充自定义数组属性

c# - 如何在 c# 中的打包记录中读取固定大小字符串的 Delphi 数组

qt - 删除 QTablewidget 中的索引号

c++ - 如何将 QString 视为文件位置并获取其目录

c++ - QOpenglWidget 和 QML Quick