C的纯虚函数实现和头文件

新手上路,请多包涵

当有问题的类分为 *.h*.cpp 文件时,我在实现从某个抽象类继承的纯虚函数时遇到了一些麻烦。编译器( g++ )告诉我,由于纯函数的存在,派生类无法实例化。

 /** interface.h**/
namespace ns
{
    class Interface {
        public:
            virtual void method()=0;
    }
}

/** interface.cpp**/
namespace ns
{
    //Interface::method()() //not implemented here
}

/** derived.h **/
namespace ns
{
    class Derived : public Interface {
        //note - see below
    }
}

/** derived.cpp **/
namespace ns
{
    void Derived::Interface::method() { /*doSomething*/ }
}

/** main.cpp **/
using namespace ns;
int main()
{
    Interface* instance = new Derived; //compiler error
}

这是否意味着我必须两次 声明 method() - 在接口的 *.hderived.h 中?没有别的办法了吗?

原文由 Neo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

您忘记声明 Derived::method()

您至少尝试定义它,但写了 Derived::Interface::method() 而不是 Derived::method() ,但您甚至没有尝试声明它。因此它不存在。

因此, Derived 没有 method() ,因此纯虚函数 method() 来自 Interface …37904fab2 和 Derived 也是纯虚拟的,不能实例化。

此外, public void method()=0; 不是有效的 C++;它看起来更像 Java。纯虚成员函数实际上必须是虚函数,但您没有写 virtual 。访问说明符后跟一个冒号:

 public:
    virtual void method() = 0;

原文由 Lightness Races in Orbit 发布,翻译遵循 CC BY-SA 2.5 许可协议

您必须在子类中声明您的方法。

 // interface.hpp
class Interface {
public:
    virtual void method()=0;
}

// derived.hpp
class Derived : public Interface {
public:
    void method();
}

// derived.cpp
void
Derived::method()
{
    // do something
}

原文由 robert 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题