如何在 Arduino 中定义类?

arduinohardwaresoftware & coding更新于 2026/2/14 21:07:17

您可以像在 C 语言中一样在 Arduino 中定义类,其中包含公共和私有变量及方法。以下示例演示了 Student 类的定义,该类包含构造函数、两个方法(add_science_marks 和 get_roll_no)以及三个私有变量:_division、_roll_no 和 _science_marks。

示例

class Student
{
   public:
      Student(char division, int roll_no);
      void add_science_marks(int marks);
      int get_roll_no();
   private:
      char _division;
      int _roll_no;
      int _science_marks;
};

Student::Student(char division, int roll_no){
   _division = division;
    _roll_no = roll_no;
}

void Student::add_science_marks(int marks){
   _science_marks = marks;
}

int Student::get_roll_no(){
   return _roll_no;
}

void setup() {
   // 在此处输入设置代码,运行一次:
   Serial.begin(9600);
   Serial.println();
   Student Yash('A',26);

   Serial.print("学生学号为:");
   Serial.println(Yash.get_roll_no());
}

void loop() {
  // 将主代码放在此处,以便重复运行:
}

输出

串行监视器输出如下所示 −

上述代码中的类声明可以放在 Student.h 文件中,函数定义可以放在 Student.cpp 文件中。这样,您就可以在 Arduino 中定义自己的库了。


相关文章