我正在寻找一种动态尺寸的二维数组的简单解决方法,它是五年级的学生可以轻松使用的参数。我目前正在为一个微控制器讲习班编写一个库,希望它尽可能简单地使用而不必解释指针,模板等,只是因为没有时间这样做。
我有一个名为LEDBitmap
的以下类,由于另一个库中的限制,该类的最大宽度为8,并且表示LED矩阵的1和0的位图:
头文件:
#ifndef LEDBITMAP_H
#define LEDBITMAP_H
#include <Arduino.h>
class LEDBitmap
{
public:
LEDBitmap(uint8_t width, uint8_t height, uint8_t data[][8]);
LEDBitmap(uint8_t width, uint8_t height);
virtual ~LEDBitmap() {
delete [] _data;
};
public: //methods
uint8_t* getBitmap();
uint8_t getPixelValue(uint8_t x, uint8_t y) {
return _data[y][x];
};
void setPixelValue(uint8_t x, uint8_t y, uint8_t value) {
_data[y][x] = value;
};
uint8_t getHeight() {
return _height;
};
uint8_t getWidth() {
return _width;
};
uint8_t getSize() {
return _width * _height;
};
void clear();
private: //members
uint8_t _width;
uint8_t _height;
uint8_t _data[][8];
};
#endif
和cpp文件:
#include "LEDBitmap.h"
LEDBitmap::LEDBitmap(uint8_t width, uint8_t height) {
_width = width;
_height = height;
_data = new uint8_t[width][height];
clear();
}
LEDBitmap::LEDBitmap(uint8_t width, uint8_t height, uint8_t data[][8]) {
_width = width;
_height = height;
_data = data;
}
uint8_t* LEDBitmap::getBitmap() {
uint8_t result[_height];
for (uint8_t h = 0; h < _height; h++) {
uint8_t binary = 0;
for (uint8_t w = 0; w < _width; w++) {
binary |= _data[h][w] << (_width - w+1);
}
result[h] = binary;
}
return result;
}
void LEDBitmap::clear() {
for (uint8_t h = 0; h < _height; h++) {
for (uint8_t w = 0; w < _width; w++) {
_data[h][w] = 0;
}
}
}
我的问题是第一个构造函数,其中参数
uint8_t data[][8]
应该是任意高度且最大宽度为8但可能更小的数组。我尝试使用模板,但意识到这将在代码的其他部分导致更大的问题。如果我要使用模板,则只能在构造函数中使用它们而不必执行
LEDBitmap<5, 5> image = ...
之类的操作,而只能使用LEDBitmap image = LEDBitmap<5, 5>(...)
我无法使用矢量,因为它们不是用C语言编写的Arduino IDE的一部分。我在C ++中拥有我的库,因为我使用的是C ++中的其他一些库,最初是想使用其他平台,但由于我最近不得不切换到Arduino的一些问题。
我当前遇到的错误是:
no known conversion for argument 3 from 'uint8_t [3][3] {aka unsigned char [3][3]}' to 'uint8_t (*)[8] {aka unsigned char (*)[8]}'
在此先感谢您的提示和帮助。
最佳答案
C ++不喜欢可变长度数组(即使在某些实现中受支持,也从未在标准中定义)或原始2D数组。如果不需要真正的[]
操作员支持,我的建议是使用访问器函数:
class Array2D {
size_t width, height;
uint8_t *data;
public:
Array2D(size_t width, size_t height): width(width), height(height() {
data = new uint8_t[width * height];
}
~Arrayt2D() {
delete[] data;
}
// copy/move ctor-assignment operator omitted for brievety but REQUIRED (law of three/five)
uint8_t getVal(size_t i, size_t j) const {
return data[i + j * width];
}
uint8_t setVal(uint8_t val, size_t i, size_t j) {
data[i + j * width] = val;
}
/* alternatively to use arr.val(i, j) = value :
uint8_t& val(size_t i, size_t j) {
return data[i + j * width];
}
*/
// other accessors (height, width) omitted but probably useful...
};
有点像C形,但是由于您不能使用向量并且更喜欢避免模板,因此它可能是一个基本的骨架...
关于c++ - 动态大小的多维数组的C++解决方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50626605/