我一直在用Tinkercad的模拟器在Arduino Uno上编写一个简单的游戏。我创建了一个名为Bullet的类和一个名为MainCharacter的类,我将其直接放入Tinkercad的代码编辑器中,因为它不能像普通的Arduino编译器那样导入多个。h和。cpp文件。
class Bullet{
private:
int xLocation;
int yLocation;
int flySpeed;
bool isBetween;
public:
Bullet(int flySpeed){
this->flySpeed = flySpeed;
}
int getX() { return xLocation;}
int getY() { return yLocation;}
int getFlySpeed() { return flySpeed;}
bool getIsBetween() { return isBetween;}
void setX(int xLocation) { this->xLocation = xLocation;}
void setY(int yLocation) { this->yLocation = yLocation;}
void setIsBetween(bool isBetween) { this->isBetween = isBetween;}
};
class MainCharacter{
private:
int xLocation;
int yLocation;
public:
MainCharacter() {}
int getX() { return xLocation;}
int getY() { return yLocation;}
void setX(int xLocation){ this->xLocation = xLocation;}
void setY(int yLocation){ this->yLocation = yLocation;}
};
这是我的代码看起来像(简化)
#include <LiquidCrystal.h>
#define ... //something
class Bullet{//above};
class MainCharacter{//above};
int game(){ //something};
Bullet spawnBullet(int flySpeed, int locationY)
{
Bullet bl = Bullet(flySpeed);
bl.setY(locationY);
bl.setIsBetween(true);
bl.setX(LENGTH_X_MAX);
return bl;
}
void setup{
//something
static MainCharacter mc = MainCharacter();
mc.setX(1);
mc.setY(0);
}
void loop{
game();
}
当我编译时,我收到'Bullet' does not name a type
指向spawnBullet
函数的错误。我不明白为什么编译器不接受在这种情况下返回用户定义类的函数,而int game()
可以工作。我试图移动类部分周围,在#include之上,或在设置部分(如果我删除spawnBullet()
函数,事情工作得很好,因为你可以看到setup()
下的MainCharacter构造函数调用仍然运行良好)。
这是我的Tinkercad项目链接:https://www.tinkercad.com/things/fWqGvbNHamj-terrific-wluff/editel?sharecode=c2_J2v4jdWwJRrVpS7k3-LPJlEf_F5z082RSwWXUhY4
我以前从未使用过tinker cad,但我设法让你的项目编译。
这是我对spawnBullet()声明的更改,这或多或少来自C,尽管一些c++17的特性,如auto在tinker cad中可以工作。
class Bullet spawnBullet(int flySpeed, int locationY)
{
//...
}
(经典)Arduino项目的主。ino文件被预处理为生成。cpp文件,我认为问题来自autodesk使用的预处理器。
我希望这样的错误不应该出现在tinker cad中,但这个解决方法至少应该允许您推进您的项目。这也可能与其他arduino预处理器不兼容,所以如果您将项目开发转移到本地计算机,您应该期望修改代码。