c++ - 将类链接到多个其他类

标签 c++ class

我的目标是在另一个类中使用一个类,这将减少整体代码并提高可读性。有一个类访问硬件,其他类应该使用该类

这是硬件类:

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/

相关文章:

c++ - visual studio 内联程序集发出字符串宏

c++ - Vector:clear/pop_back 不会运行析构函数

python - 如何在不出现 MRO 错误的情况下动态添加 mixin 作为基类?

c++ - 二进制表达式的无效操作数(C++ 运算符重载)

class - 方法未定义(类型没有方法)

c++ - 如果您必须检查溢出或有条件地采取行动, std::atomic 是否多余?

c++ - C++中的多重继承与虚函数

C++ SIMD : Store uint64_t value after bitwise and operation

class - F# 类型类持久计数器

c# - 调用继承方法和基方法