Neo*_*Neo 11 c++ inheritance abstract pure-virtual
当有问题的类被分成*.h
和时,我在实现从一些抽象类继承的纯虚函数时遇到了一些麻烦*.cpp
.compiler(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
}
Run Code Online (Sandbox Code Playgroud)
这是否意味着我必须两次声明方法() - 在接口*.h
和它中也是derived.h
如此?没有别的办法吗?
Lig*_*ica 15
你忘了申报Derived::method()
.
你试图至少定义它,但写Derived::Interface::method()
而不是Derived::method()
,但你甚至没有尝试声明它.因此它不存在.
因此,Derived
没有method()
,因此纯虚函数method()
从未Interface
被覆盖...因此,Derived
也是纯虚拟的,无法实例化.
另外,public void method()=0;
是无效的C++; 它看起来更像Java.纯虚拟成员函数实际上必须是虚拟的,但是你没有写virtual
.访问说明符后面跟冒号:
public:
virtual void method() = 0;
Run Code Online (Sandbox Code Playgroud)
rob*_*ert 13
您必须在子类中声明您的方法.
// 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
}
Run Code Online (Sandbox Code Playgroud)