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

标签 c++ inheritance abstract pure-virtual

当有问题的类分为 *.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() 两次 - 在接口(interface)的 *.hderived.h 中也?就没有别的办法了吗?

最佳答案

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

// 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
}

关于C++的纯虚函数实现和头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4675590/

相关文章:

java - 如何强制在我的抽象类的所有子类中定义构造函数

通过通用父类访问的子类中的 Java 静态成员

c++ - 编译器的健壮性……天真

具有泛型和继承的 java 抽象类 : Bound mismatch

c++ - 在 boost geometry c++ 库中我添加的点的顺序有关系吗?

python - 在 `super()` 内使用 `__init_subclass__` 找不到父类的类方法

c++ - 在 C++ 中继承私有(private)成员

c++ - 虚表和多态性

c++ - NS3 套接字混淆(需要帮助理解)

c++ - 尝试在 Visual Studio 2013 中使用 sqlite3_open 进行编译时出错