当有问题的类分为 *.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() - 在接口的 *.h
和 derived.h
中?没有别的办法了吗?
原文由 Neo 发布,翻译遵循 CC BY-SA 4.0 许可协议
您忘记声明
Derived::method()
。您至少尝试定义它,但写了
Derived::Interface::method()
而不是Derived::method()
,但您甚至没有尝试声明它。因此它不存在。因此,
Derived
没有method()
,因此纯虚函数method()
来自Interface
…37904fab2 和Derived
也是纯虚拟的,不能实例化。此外,
public void method()=0;
不是有效的 C++;它看起来更像 Java。纯虚成员函数实际上必须是虚函数,但您没有写virtual
。访问说明符后跟一个冒号: