如何在 Arduino 中定義一個類?
你可以像在 C 中那樣在 Arduino 裡定義一個類,其具有公共變數和方法以及私有變數和方法。下面的示例展示了 Student 類的定義,它具有構造方法、兩個方法(add_science_marks 和 get_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 中定義自己的庫了。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP