gpt4 book ai didi

c++ - 在许多不同的类中调用相同的函数

转载 作者:行者123 更新时间:2023-11-28 01:41:34 25 4
gpt4 key购买 nike

为了简化我的代码,我希望使用可以存储多个对象的数组,之后可以调用这些对象中的函数。

我创建了许多具有(部分)相同成员函数的类。当然这些功能有不同的实现。我希望将这些对象放在一个数组中,之后我可以遍历它并调用这些函数。

我有很多传感器,我们称它们为 Sensor1、Sensor2 和 Sensor3。它们都有一个名为 readSensor() 的函数和一个名为 sensorData() 的函数。 (第一个读取传感器,第二个返回一行 html - 在我的实际软件中有大约 10-12 个传感器和 4 个这样的函数,因此我希望简化代码并使添加传感器更容易)。

所以我想做的是这样的:

Sensor1 sensor1;
Sensor2 sensor2;
Sensor3 sensor3;
byte nSensors = 3;

(type?) *sensorList[nSensors] // list of pointers to the sensors - don't know how to declare this.

void setup() { // yes, this is for Arduino.
sensorList[0] = &sensor1; // store the pointers to the class objects.
sensorList[1] = &sensor2;
sensorList[2] = &sensor3;
}

void readSensors () {
for (int i=1, i<nSnesors, i++) {
sensorList[i]->readSensor();
}
}

这样我就可以读取所有传感器,而不必写出所有传感器并希望我不会忘记任何一个。使代码更短,我可以在一个地方添加传感器。该数组仅用于所有传感器具有的功能(尽管实现不同,但名称相同——毕竟这是不同的传感器)。这些对象也有一些特定于传感器的函数,需要时可以直接调用。

这有可能吗?如果是,怎么办?

最佳答案

您可以简单地使用运行时多态性来完成这项工作。

例子:

class SensorBase
{
public:
virtual void readSensor() = 0;
virtual void getData(char*) = 0;
};

class Sensor1: public SensorBase
{
void readSensor() { std::cout << "read for Sensor1 called" << std::endl; }
void getData(char* ptr) { std::cout << "get for Sensor1 called" << std::endl; }
};

class Sensor2: public SensorBase
{
void readSensor() { std::cout << "read for Sensor2 called" << std::endl; }
void getData(char* ptr) { std::cout << "get for Sensor2 called" << std::endl; }
};

// Static allocate objects, new is not a good idea for small embedded devices
// cause of significant overhead. Global objects are typically a design problem,
// but small embedded systems have different requirements ;)

Sensor1 sensor1;
Sensor2 sensor2;

// lets have array to objects, statically allocated
SensorBase* arr[] = { &sensor1, &sensor2 };


int main()
{
char htmlString[256];

for ( auto ptr: arr )
{
ptr->readSensor();
ptr->getData( htmlString );
}
}

您必须根据需要删除示例函数的内容。 std::cout 仅在此处用于让应用程序以可见输出运行,作为工作原理的示例。

您使用 setup代码中的方法。这在更大的系统上可能是个好主意,但在 avr 上不是!如果您像我给出的示例那样使用静态分配,您的代码将会更小更快。如果您给编译器一些提示以将某些数据字段或类存储在闪存中,则可以加快速度。对于该主题,请考虑 #include <avr/pgmspace.h>

也许你必须用 constexpr 来编写你的类能够将数据存储在闪存中的构造函数。使用虚拟方法必须注意:gcc 不能将它们存储在闪存中。这是一个非常老的错误/设计问题,会浪费您的小设备的大量内存。切换到 arm 设备的原因之一!参见 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=43745 .如果您的代码中需要大量多态类,这会使 avr gcc 无法使用。这个错误不会被修复!

关于c++ - 在许多不同的类中调用相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46908301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com