Arduino C++在构造函数中用参数声明对象数组
Arduino C++ Declare array of objects with parameters in constructor
我只想声明一个大小为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次。为了避免这种情况,你有两个选择:
- 使用默认构造函数:
control(char* controlName = "controlArray");
可能对您有用,但前提是您计划初始化具有相同值的所有数组。
- 如果使用
gcc
,您可以使用它的扩展来初始化它,如下所示:
control controlArray[5] = {[0 ... 4] = "controlArray"};
但这只适用于gcc
,因此对可移植性不太好。
此外,与你的问题无关——我认为你可能是想复制字符串,而不是将指针存储在类中,所以你应该在构造函数中使用类似strncpy
的东西,而不仅仅是分配给name
,在这种情况下,您必须为name
预先分配存储(或者像char name[255];
一样将其声明为char数组,在构造函数中为其分配空间,或者使用std::string
使其更容易(。
相关文章:
- Arduino C++在构造函数中用参数声明对象数组
- 如何使用参数声明实例?
- 从非类型模板参数声明 constexpr 数组的可移植方法
- 用相同的参数声明两个构造函数的最偶像化的方法是什么?
- 在实现文件中使用模板参数声明方法
- 使用 std::move 将参数传递给函数,如果该参数声明为按值传递或使用移动操作数 &&,是否有区别?
- 如果我提前将参数声明为变量而不是将它们内联写入函数调用,那有什么区别(在内存方面)?
- 为什么重载运算符>在参数声明 const 时不起作用?
- 字符串无法启动参数声明
- 视觉C++:即使使用关键字,参数声明也会隐藏类成员"this"
- C 迭代器从Typedef std :: Map作为模板参数声明
- 参数声明中的"const T const"
- 如何处理"警告:在参数声明中使用'auto'仅适用于 -fconcepts"
- 将容器作为模板参数声明过滤
- 同时使用模板和参数声明对象
- 从variadic模板参数声明成员变量
- 在 C++ 中,为什么我们在重载函数中将引用参数声明为 const
- 在C++中,是否可以使用定义中未使用的模板参数声明模板结构?
- C++ "无法将参数声明为抽象类型
- 默认参数声明:为什么默认字符串参数必须是 const