我正在做一个小游戏,想存储高分。我在草图文件的顶部创建了一个Highscore类,如下所示:
class Highscore {
public:
String name;
int score;
String toString() {
return this->name + " - " + (String)score;
}
Highscore(String name, int score) {
this->name = name;
this->score = score;
}
};
setup() { // etc
现在。在草图底部附近,我有一个函数希望将Highscore对象作为参数,但是编译器不允许我这样做。例:
void writeHighscore(Highscore hs) {
File f = SD.open("high.txt", FILE_WRITE);
// Do stuff
编译错误如下:
sketch.ino:19:21:错误:变量或字段'writeHighscore'声明为void
sketch.ino:19:21:错误:未在此范围内声明'
Highscore'sketch.ino:在函数'void setup()'中:
sketch.ino:64:20:错误:未在此范围内声明'writeHighscore'
将参数类型更改为String,int或其他任何类型后,所有错误都会消失。我可以在writeHighscore()
函数内部创建Highscore-objects ,但是如何将对象传递给它呢?
编辑1-对象创建
Highscore hs = Highscore("John", 975);
Serial.println(hs.toString()); // Prints "John - 975" as expected
writeHighscore(hs); // Error
&hs
写帖子之前,我还尝试了该方法,还通过了指针writeHighscore(&hs)
-> void writeHighscore(Highscore *hs)
但无济于事。