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

标签 c++ inheritance virtual pure-virtual

下面是我要实现的纯虚接口(interface)类:

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

最佳答案

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

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

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

关于c++ - 无法使用 const struct timepec 覆盖纯虚函数*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35375217/

相关文章:

c++ - 用C++编译器编译C99文件

c++ - 在 Qt 中正确使用进度条?

java - 关于Java中的抽象类和Hibernate注解

c++11 - 无法使用 SFINAE (std::enable_if) 覆盖虚函数

macos - VirtualHere 如何在 macOS 上创建虚拟 USB 设备?

c++ - 发送类实例时是否会调用覆盖,就好像它是没有覆盖的类型一样?

c++ - mariadb make_query 卡在 make_query() 调用中

c++ - 无法在 map 的 map 的 STL map 中插入数据

inheritance - 如何使用相同的类名扩展 dart 中的类

asp.net - NHibernate 继承类但无需持久化