在C++中实现方法时继承不起作用

Inheritance not working when implementing method in C++

本文关键字:继承 不起作用 方法 实现 C++      更新时间:2023-10-16

我有 2 个文件正在处理:encoder.hencoder.cc

据我所知,继承的方法(初始化和读取)应该在MotorEncoder类中可用。但是,当我尝试实现这些方法时,编译器会抛出错误。有什么想法吗?

页眉

class Encoder {
protected:
    u32 bitResolution;
    SPI spi;
public:
    void initialize(u16 spiDeviceID, u32 bitResolution);
    u32 read();
};
class MotorEncoder : public Encoder {
public:
// If I comment these 2 lines it SHOULD work as far as I know, 
// but it won't compile due to the method not being defined when 
// implementing e.g. in MotorEncoder::initialize()
void initialize(u16 spiDeviceID, u32 bitResolution);
u32 read();
};

实现

void Encoder::initialize(u16 spiDeviceID, u32 bitResolution) {
    // ....
}
u32 Encoder::read() {
    //
}

void MotorEncoder::initialize(u16 spiDeviceID, u32 bitResolution) {
    // implementation
}
u32 MotorEncoder::read() {
    // implementation code
}

基类和派生类中的方法当前不相关。他们只是碰巧有相同的名字。

完整的调用表达式将是 this->Encoder::read()this->MotorEncoder::read() 。你可以省略this->,不合格的read()会引用MotorEncoder::read(),但它们仍然是两个函数。

也就是说,我认为你对继承有一个更根本的误解。你不需要声明或定义MotorEncoder::read,正是因为它已经被继承了。您可能还想阅读 virtual .

initialize是另一个令人担忧的迹象。在C++中,初始化由构造函数完成。