如何在 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