[英]Arduino - Creating an Array from instances and assigning value [C++]
我在C ++和数组上搜索了很多资源。 我了解到数组在c ++中的作用类似于指针,而我对如何创建多维数组以及为索引分配值感到困惑。 我通常使用Java和Python进行编码,但知道我正在使用Arduino,并且需要学习c ++。
关于此数组的我的Arduino(c ++)代码为:
#include "Arduino.h"
#include "cell.h"
#include <cell.h>
cell maze[16][16];
cell * current = new cell(1, 1, 0, false, 0);
cell * end_pt = new cell(1,1,1,true);
maze[15][15] = end_pt;
我的.h和.cpp文件;
#include "Arduino.h"
#include "cell.h"
#include "Arduino.h"
cell::cell(){
right = 0;
}
cell::cell(int r, int l, int f, bool inf){
right = r;
left = l;
forw = f;
info = inf;
value = 70;
printf("%d\n", right);
printf("%d\n", left);
printf("%d\n", forw);
printf("%d\n", inf);
printf("%d\n", val);
}
cell::cell(int r, int l, int f, bool inf, int val){
right = r;
left = l;
forw = f;
info = inf;
value = val;
printf("%d\n", right);
printf("%d\n", left);
printf("%d\n", forw);
printf("%d\n", inf);
printf("%d\n", val);
}
void cell::setR(int r){
right = r;
}
void cell::setL(int l){
left = l;
}
void cell::setF(int f){
forw = f;
}
void cell::setI(bool inf){
info = inf;
}
void cell::setV(int val){
value = val;
}
int cell::getR(){
return right;
}
int cell::getL(){
return left;
}
int cell::getF(){
return forw;
}
bool cell::getI(){
return info;
}
int cell::getV(){
return value;
}
#ifndef cell_h
#define cell_h
#include "Arduino.h"
class cell{
public:
cell();
cell(int r, int l, int f, bool info);
cell(int r, int l, int f, bool info, int val);
void setR(int r);
void setL(int l);
void setF(int f);
void setI(bool inf);
void setV(int val);
int getR();
int getL();
int getF();
bool getI();
int getV();
private:
int right;
int left;
int forw;
bool info;
int value;
};
#endif
“迷宫”没有命名类型是我的错误。 请帮助并提前感谢您!
这条线有问题:
maze[15][15] = end_pt;
maze[15][15]
和迷宫中的任何其他对象都是cell
类型
end_pt
的类型为cell*
这意味着您正在尝试分配两种不同的类型。
相反,请执行以下操作:
cell end = cell(1,1,1,true);
maze[15][15] = end;
要不就
maze[15][15] = cell(1,1,1,true);
由于您使用的是C ++,请考虑改用std::array
。 并尽可能避免新的/删除的内容。
“迷宫”没有命名类型
实际上,“迷宫”不会命名类型。 实际上,它是一个对象。
在其他语言中,您可以在函数外部编写指令,因为整个文件正文都被视为“函数”。 但是,在C中,外部函数只能编写全局变量的声明和定义。 您应该已经写过:
#include "Arduino.h"
#include "cell.h"
#include <cell.h>
cell maze[16][16];
cell * current = new cell(1, 1, 0, false, 0);
cell * end_pt = new cell(1,1,1,true);
void setup()
{
maze[15][15] = end_pt;
}
现在,正如另一个答案指出的那样,您无法为该值分配指针。 如果要将迷宫作为单元矩阵,则必须手动复制值:
void copyCell(cell *dst, cell src)
{
dst->right = src.right;
dst->left = src.left;
dst->forw = src.forw;
dst->info = src.info;
dst->value = src.value;
}
void setup()
{
copyCell(&(maze[15][15]), end_pt);
}
(或者最好在类中包含一个复制函数)
或将迷宫声明为单元格指针矩阵:
cell *maze[16][16];
这取决于您要如何实现该程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.