使用const struct timepec*无法覆盖纯虚函数
override pure virtual function not possible with const struct timepec*
下面是我想要实现的纯虚拟接口类:
#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 库有时会这样做(。
相关文章:
- 专门化模板覆盖函数/避免对象切片
- 为什么编译器不检查被覆盖函数的存储类?
- 如何使基类从子类调用覆盖函数
- 为什么 MSVC 在使用正确的签名覆盖函数时会产生 C3668 错误?
- 为什么调用具有通用或 r 值引用的重载覆盖函数是不明确的?
- 如何在C++中覆盖函数
- Arduino 可覆盖函数
- 为什么我们不能在C++中覆盖函数指针?
- 在多级继承中重写,中间派生类未覆盖函数
- C++获取指向受保护覆盖函数的指针
- 内联失败:可以在链接时覆盖函数体
- C++ 调用覆盖函数会导致调用基函数
- C++虚拟覆盖函数链接器错误
- 如何使用函数 b(C & winapi)覆盖函数 a?
- 用于在多重继承中覆盖函数的语法
- Cocos2DX 中的覆盖函数
- 使用覆盖函数的继承
- C++ 调用从基类派生的覆盖函数
- 如何在 C++ 中的常量覆盖函数中调用 no-const 函数
- 如何在运行时覆盖 C 函数(如 LD_PRELOAD)