我想在我的类中创建一个常量(最好是静态但不是必需的)成员变量。
我希望它是一个 3 维数组,每个长度大小为 2。
目的:针对 3 种类型的 bool 选择的组合,存储一些在每次更改时重新创建耗时的数据,而无需对每次更改进行复杂的测试。
我不知道该怎么做:如何初始化 3D 数组。
这就是我正在尝试的(基于 cplusplus.com/forum/Multi-Dimensional Arrays ):
class MyClass {
public: ...
~MyClass(); // will I need to destroy m_previewIcons to prevent memory leak ?
private: ...
static const QIcon m_previewIcons[2][2][2]; // the array I need
static QIcon*** initializePreviewIcons(); // what type of return ?
};
const QIcon MyClass::m_previewIcons[2][2][2] = MyClass::initializePreviewIcons();
QIcon ***MyClass ::initializePreviewIcons()
{
QIcon ***iconArray = 0;
// Allocate memory
iconArray = new QIcon**[2];
for (int i = 0; i < 2; ++i)
{
iconArray[i] = new QIcon*[2];
for (int j = 0; j < 2; ++j)
iconArray[i][j] = new QIcon[2];
// is this even right ? it seems to me I miss out on a dimension ?
}
// Assign values
iconArray[0][0][0] = QIcon(":/image1.png");
iconArray[0][0][1] = QIcon(":/image2.png"); ...
iconArray[1][1][1] = QIcon(":/image8.png");
return iconArray;
}
据我所知...
error: conversion from 'QIcon***' to non-scalar type 'QIcon' requested
我怎样才能让这个初始化工作?
注意 - QIcon
是 Qt 中的内置类,这是我使用的(任何类都相同)。
虽然没有 C++ 11。
我想我本可以使用 vector ,但我想要更少的开销。
编辑:我刚刚想到了另一种方法...放弃 3D 数组,使用简单的 1D 数组并使用移位的 bool 值为索引构建一个 int。可能更有效。
但我仍然想知道如何初始化 3D 数组。
最佳答案
你正在创建一个静态数组,然后尝试动态分配它的内存,这不是必需的 - 由于你的声明 static const QIcon m_previewIcons[2][2][,内存已经存在了2];
你应该使用列表初始化来初始化你的 3d 数组,la this answer .
这是一个非 POD 类型的示例,std::string:
#include <string>
class MyClass {
public:
static const std::string m_previewIcons[2][2][2];
};
const std::string MyClass::m_previewIcons[2][2][2] = {
{ {":/image1.png",":/image2.png"},
{":/image3.png",":/image4.png"} },
{ {":/image5.png",":/image6.png"},
{":/image7.png",":/image8.png"} }
};
int main()
{
MyClass mc;
printf("%s\n", mc.m_previewIcons[0][0][0].c_str());
}
关于c++ - 初始化const 3D数组成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42699360/