使用const struct timepec*无法覆盖纯虚函数

override pure virtual function not possible with const struct timepec*

本文关键字:覆盖 函数 const struct timepec 使用      更新时间:2023-10-16

下面是我想要实现的纯虚拟接口类:

#include <time.h>
class SharedMemoryInterface
{
public:
    virtual ~SharedMemoryInterface() {}
    virtual int sem_timedwait(sem_t* sem, const struct timepsec* abs_timeout) = 0; 
};

以下是实现:

class SharedMemoryImpl : public SharedMemoryInterface
{
public:
    virtual int sem_timedwait(sem_t* sem, const struct timespec* abs_timeout) { return ::sem_timedwait(sem, abs_timeout); }
};

我收到编译器错误:

SharedMemoryImpl.h:25:7: note:   because the following virtual functions are pure within "SharedMemoryImpl":
 class SharedMemoryImpl : public SharedMemoryInterface
SharedMemoryInterface.h:27:17: note:    virtual int SharedMemoryInterface::sem_timedwait(sem_t*, const timepsec*)
     virtual int sem_timedwait(sem_t* sem, const struct timepsec* abs_timeout) = 0;

唯一的区别似乎是在 timespec 参数上,它删除了结构并且原型不再匹配,为什么要这样做?

你在SharedMemoryInterface::sem_timedwait中有一个错别字:你写的是timepsec而不是timespec

通常这会导致错误,但您使用了 struct 关键字。当编译器看到struct timepsec时,它要么找到一个名为 timepsec 的结构(忽略任何同名的函数(,要么如果找不到它,则向前声明一个新结构。因此,使用struct掩盖了错别字。当你在SharedMemoryImpl中正确拼写timespec时,当然它指的是不同的类型。因此,SharedMemoryInterface中的纯虚函数不会被覆盖。

AFAIK,没有编译器警告可以捕获这些拼写错误的前向声明。在C++中,我建议简单地避免使用详细的类型说明符是一种很好的做法,除非你真的需要你的代码同时用 C 和 C++ 编译(显然,这里不是这种情况(,或者你需要引用与函数同名的结构/类(显然,以这种方式命名是不好的, 但 C 库有时会这样做(。