我在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
'迷宫'没有命名类型是我的错误。请提前帮助并表示感谢!
答案 0 :(得分:1)
这条线存在问题:
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
。并尽可能避免新的/删除。
答案 1 :(得分:1)
'迷宫'没有命名类型
事实上,'迷宫'并不是一种类型。这确实是一个对象。
在其他语言中,您可以在函数外部编写指令,因为整个文件正文被视为“函数”。但是,在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];
这取决于您希望如何实施该计划