C++ / Arduino:动态int数组
我正在为 Arduino 编写一个类。到目前为止一切进展顺利,但我现在有点卡住了......
我在我的类中声明了一个 int 数组
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
当我初始化类 MyClass myClass1(5)
我需要数组来查看像这样的 {0,0,0,0,0}。
我的问题:我需要做什么才能使数组包含“大小”数量的零?
MyClass::MyClass(int size)
{
//what goes here to dynamically initialize the array
for(int i=0; i < size; i++) _intArray[i] = 0;
}
编辑:根据下面的各种回复,Arduino 不包含标准库,因此不幸的是 std::vector
不是一个选项
I'm writing a class for the Arduino. It's been going well so far, but I'm sort of stuck now...
I have declared an int array in my class
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
When I initialize the class MyClass myClass1(5)
I need the array to look like this {0,0,0,0,0}.
My question: what do I need to do so that the array contains 'size' amount of zeros?
MyClass::MyClass(int size)
{
//what goes here to dynamically initialize the array
for(int i=0; i < size; i++) _intArray[i] = 0;
}
Edit: Following up on various replies below, Arduino does not include the standard library so unfortunately std::vector
is not an option
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我写下的代码是:
_intArray
的声明不是有效的 C++:原始数组需要在编译时指定大小。您可以改为使用
std::vector
:注 1:某些编译器可能允许您的原始代码作为语言扩展,以支持“struct hack”(这是 C 技术,在 C++ 中不是必需的)。
注2:我更改了您的会员姓名。通常,名称开头的下划线可能会出现问题,因为它们可能与 C++ 实现中的名称冲突。
干杯&呵呵,
Your code as I'm writing this:
The declaration of
_intArray
is not valid C++: a raw array needs to have a size specified at compile time.You can instead instead use a
std::vector
:Note 1: some compilers may allow your original code as a language extension, in order to support the "struct hack" (that's a C technique that's not necessary in C++).
Note 2: I've changed the name of your member. Generally underscores at the start of names can be problematic because they may conflict with names from the C++ implementation.
Cheers & hth.,
您应该使用 std::vector。
You should use a std::vector.
你真的应该像其他人建议的那样使用向量。解决方法可能如图所示(如果您不想使用 memcpy 或循环)。
如果你有一个非常大的数组,这将很有用。请注意,它将添加一个间接级别来访问数组。
You should really use vectors as others have suggested. A work-around could be as shown (in case you do not want to use memcpy or a loop).
This would be useful if you have a really huge array. Note that it would add a level of indirection to access the array.
我将尝试以下操作:
或者,更好的是,使用 STL
vector
代替......I'll try the following:
Or, even better, use a STL
vector
instead ...您可以使用另一个基于字符串值的黑客,然后填充有限大小的数组
检查这个:
https://github.com/Riadam/ViewPort-Array- Arduino-Uno 移位器.git
you can use another hack basing on a string value and then populate a limited size array
check this :
https://github.com/Riadam/ViewPort-Array-Shifter-for-Arduino-Uno.git