模块化编程:C++写嵌入式代码

模块化编程:C++写嵌入式代码 上面例子要是加上每个对象自己的数据就更直观了// 在 .cpp 中 static TempSensor* sensorList[10]; static int sensorCount 0; class TempSensor { public: TempSensor(uint8_t addr) : address(addr) { // 点睛之笔出生即注册 if(sensorCount 10) { sensorList[sensorCount] this; } } // 统一的中断处理接口 virtual void onDataReceived(float temp) { // 处理具体逻辑 } }; // 模拟硬件中断回调 void HAL_I2C_MasterRxCpltCallback(...) { uint8_t id getSenderId(); float data getData(); // 通用路由逻辑永远不需要改这段代码 for(int i0; isensorCount; i) { if(sensorList[i]-address id) { sensorList[i]-onDataReceived(data); // 多态调用 break; } } } // main.cpp TempSensor t1(0x48); // 自动注册 TempSensor t2(0x49); // 自动注册 TempSensor t3(0x4A); // 自动注册 // 即使以后加了 t4, t5...t10上面的中断回调代码一行都不用动