我的目标是在另一个类中使用一个类,这将减少整体代码并提高可读性。有一个类访问硬件,其他类应该使用该类
这是硬件类:
class NFC:NFC(int buspin, int datapin, int resetpin, int cspin, int *param)
类内是:
NFC::getDatablock(uint8_t address, uint8_t *data);
现在有“配置”和“历史”类需要从 NFC 类读取和写入数据。
目前我的解决方案如下:
NFC reader(1,2,3,4,x);
CONFIG configuration();
//read configuration from reader
uint8_t configuration[64]={};
reader.getDatablock(3, &configuration);
//transfer data to config:
configuration.importData(&configuration);
//save data
uint8_t newData[64])={};
configruation.getdata(&newData);
//transfer to reader
reader.write(1,&configuration
这需要在“主”应用程序中添加此代码,因为 main.cpp 知道所有类。如果可以直接调用:
configuration.getConfig();
以及函数内部:
void configuration::getConfig(){
uint8_t db[64] = {};
reader.getDatablock(3, &configuration);
...
}
有办法实现这一点吗?
最佳答案
有两个选项:
选项 1:
您将在 Reader 类型的 Configuration 类中创建一个私有(private)变量,然后在接受 Reader 实例的 Configuration 类的构造函数中添加一个参数。然后,您可以将此实例分配给 Configuration 类中的私有(private)实例变量。
然后在 Configuration::getConfig()
中,您可以通过私有(private)实例变量访问 Reader 实例。
配置.h
Class Config {
public:
Config(Reader *reader);
void getConfig();
private:
Reader *_reader;
配置.cpp
Config::Config(Reader *reader){
_reader = reader;
}
void Config::getConfig(){
...
_reader.getDatablock(...)
...
}
选项 2:
正如 @mcabreb 所说,您可以通过阅读器实例作为 getConfig() 中的参数发送
Config.h
Class Config{
...
void getConfig(Reader *reader);
配置.cpp
void getConfig(Reader *reader){
...
reader.getDatablock(...)
...
}
关于c++ - 将类链接到多个其他类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56233083/