如何在 Arduino 中定義一個類?


你可以像在 C 中那樣在 Arduino 裡定義一個類,其具有公共變數和方法以及私有變數和方法。下面的示例展示了 Student 類的定義,它具有構造方法、兩個方法(add_science_marksget_roll_no)和 3 個私有變數,_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() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   Student Yash('A',26);

   Serial.print("Roll number of the student is: ");
   Serial.println(Yash.get_roll_no());
}

void loop() {
   // put your main code here, to run repeatedly:
}

輸出

序列埠監視器輸出如下所示 -

上述程式碼中的類宣告本可以放在 Student.h 檔案中,函式定義則可以放在 Student.cpp 檔案中。如此,你便可以在 Arduino 中定義自己的庫了。

更新於: 30-7-2021

7K+ 瀏覽量

開啟您的職業生涯

完成課程認證

開始
廣告
© . All rights reserved.