当有问题的类分为 *.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)的 *.h
和 derived.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/