我正在做一个嵌入式项目,需要各种类型的温度传感器。这是我的尝试:
typedef int pinNumber_t;
typedef int i2cInterface_t;
class tempSensor {
public:
// this method MUST be defined in the derived classes (pure virtual)
virtual float
operator() (void) const = 0;
};
class analogInTempSensor : public tempSensor {
private:
pinNumber_t pin;
public:
analogInTempSensor(pinNumber_t x) {
pin = x;
};
float
operator() (void) const {
float temp = 0;
// acquire the value
// correct the value
return(temp);
};
};
class i2cTempSensor : public tempSensor {
private:
i2cInterface_t i2c;
public:
i2cTempSensor(i2cInterface_t x) {
i2c = x;
};
float
operator() (void) const {
float temp = 0;
// acquire the value
// correct the value
return(temp);
};
};
// TIME TO DESCRIBE THE HARDWARE...
// array of temperature sensors
tempSensor tempSensorArray[] = {
analogInTempSensor(0),
i2cTempSensor(0)
};
int main(void) {
}
编译时,我得到:
./test.cpp:64:28: error: invalid abstract type ‘tempSensor’ for ‘tempSensorArray’
tempSensor tempSensorArray[] = {
^
./test.cpp:5:7: note: because the following virtual functions are pure within ‘tempSensor’:
class tempSensor {
^~~~~~~~~~
./test.cpp:11:5: note: ‘virtual float tempSensor::operator()() const’
operator() (void) const = 0;
^~~~~~~~
./test.cpp:67:1: error: cannot allocate an object of abstract type ‘tempSensor’
};
^
./test.cpp:67:1: error: cannot allocate an object of abstract type ‘tempSensor’
我如何才能得到一个对象数组或指向不同类但都从同一基类派生的对象的指针?定义好之后,我希望所有温度传感器都一样。我的计划是遍历数组以获取所有各种温度。