Arduino C++在构造函数中用参数声明对象数组

Arduino C++ Declare array of objects with parameters in constructor

本文关键字:参数 声明 对象 数组 C++ 构造函数 Arduino      更新时间:2023-10-16

我只想声明一个大小为5的control类对象数组。之后将填充特定对象的内容。

class control {
public:
control(char* controlName) {
name = controlName;
}
private:
char* name;
};
void setup() {
control humidityControl("humidityControl");
// Problem: Declare an array controlArray with the size of 5 and the name "controlArray"
control controlArray[5]("controlArray"); // Error: no matching function for call to 'control::control()'
control controlArray("controlArray")[5]; // Error: expected ',' or ';' before '[' token
}

void loop() {
}

我在我的Arduino上使用C++。我会感谢每一个小费如何解决这个问题。谢谢

您的问题是将数组的声明(方括号(与对构造函数的调用混合在一起。SO的回答澄清了这一点:https://stackoverflow.com/a/1598409/2881667.

你想做的是:

void setup() {
control controlArray[5] = {"controlArray", "controlArray", "controlArray", "controlArray", "controlArray"};
}

请注意,您必须将参数包含到构造函数中5次。为了避免这种情况,你有两个选择:

  1. 使用默认构造函数:
control(char* controlName = "controlArray");

可能对您有用,但前提是您计划初始化具有相同值的所有数组。

  1. 如果使用gcc,您可以使用它的扩展来初始化它,如下所示:
control controlArray[5] = {[0 ... 4] = "controlArray"};

但这只适用于gcc,因此对可移植性不太好。

此外,与你的问题无关——我认为你可能是想复制字符串,而不是将指针存储在类中,所以你应该在构造函数中使用类似strncpy的东西,而不仅仅是分配给name,在这种情况下,您必须为name预先分配存储(或者像char name[255];一样将其声明为char数组,在构造函数中为其分配空间,或者使用std::string使其更容易(。