【问题标题】:override pure virtual function not possible with const struct timepec*使用 const struct timepec* 覆盖纯虚函数是不可能的
【发布时间】:2016-05-24 08:20:15
【问题描述】:

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

#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 参数中,它删除了结构并且原型不再匹配,为什么要这样做?

【问题讨论】:

标签: c++ inheritance virtual pure-virtual


【解决方案1】:

您在SharedMemoryInterface::sem_timedwait 中有错字:您写的是timepsec 而不是timespec

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

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

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2013-10-04
    • 2021-09-30
    • 2020-08-21
    • 2021-11-01
    • 2016-02-05
    • 2014-05-22
    • 2020-08-01
    • 2013-01-16
    相关资源
    最近更新 更多