我的Arduino项目中有一个类(Arduino基本上只是C ++)。我有一个称为“画布”的二维数组。我想在类的开头将数组初始化为变量。我的班级中有一个函数,用于将所需的画布尺寸传递给班级。我想从此函数内部以正确的尺寸创建此数组,但是数组的范围将不是全局的。
如何执行此操作,以便可以将数组创建为全局类变量,但可以在函数内部设置数组的大小?
编辑以弄清楚,这就是我想要发生的情况:
class foo{
int canvas[][];
void setupCanvas(int canvasX, int canvasY){
//I want to set the size of array "canvas" here.
//my other option is to initialise the array "canvas" here with
//dimensions canvasX and canvasY.
//Obviously that wouldn't work because I need this variable to
//be global.
}
};
答案 0 :(得分:0)
希望您的问题是您不知道如何在类中动态创建成员数组。
using namespace std;
// create your class
class MyClass {
int m_canvasX; // we need store the array size somewhere
public:
int** m_canvas;
// assign a value to your member in a method
void setupCanvas(const int canvasX = 1, const int canvasY = 1){
m_canvasX = canvasX;
m_canvas = new int*[canvasX];
for(int x = 0; x < m_canvasX; x++)
m_canvas[x] = new int[canvasY];
// store a value for demonstration
m_canvas[canvasX-1][canvasY-1] = 1234;
}
~MyClass(){
for(int x = 0; x < m_canvasX; x++)
delete[] m_canvas[x];
delete[] m_canvas;
}
};
int main(){
// create an instance of your class
int sizeX = 2;
int sizeY = 3;
MyClass example;
example.setupCanvas(sizeX, sizeY);
// print the value to proof that our code actually works
cout << example.m_canvas[sizeX-1][sizeY-1];
return 0;
}
答案 1 :(得分:0)
在arduino上,空间通常非常有限,这意味着通常应避免使用动态内存管理,因为这会导致较长时间的内存碎片。
以下解决方案本身不使用动态分配:
constexpr int foo_max_elements = 1024;//use #define instead if compiler doesn't support constexpr
class foo{
int canvas[foo_max_elements];
int size_x;
int size_y;
public:
void foo(int canvasX, int canvasY) : size_x{canvasX}, size_y{canvasX} {
if (size_x*size_y > foo_max_elements ) {
//too large: handle error
}
}
};
主要缺点是该解决方案总是消耗相同数量的存储空间,这意味着浪费较小的对象。