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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4675590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:07:51  来源:igfitidea点击:

C++'s pure virtual function implementation and header files

c++inheritanceabstractpure-virtual

提问by Neo

I'm having some trouble implementing pure virtual functions inherited from some abstract class, when the classes in question are divided into *.hand *.cppfiles. The compiler (g++) tells me that the derived class cannot be instantiated because of the existence of pure functions.

当有问题的类被分为*.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
}

Does this mean that I have to declarethe method() twice - in the Interface's *.hand in the derived.htoo? Is there no other way around?

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

回答by Lightness Races in Orbit

You forgot to declare Derived::method().

你忘记申报了Derived::method()

You tried to define it at least, but wrote Derived::Interface::method()rather than Derived::method(), but you did not even attempt to declare it. Therefore it doesn't exist.

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

Therefore, Derivedhas no method(), therefore the pure virtual function method()from Interfacewas not overridden... and therefore, Derivedis also pure virtual and cannot be instantiated.

因此,Derivedhas no method(),因此纯虚函数method()fromInterface没有被覆盖......因此,Derived也是纯虚函数,不能被实例化。

Also, public void method()=0;is not valid C++; it looks more like Java. Pure virtual member functions have to actually be virtual, but you did not write virtual. And access specifiers are followed by a colon:

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

public:
    virtual void method() = 0;

回答by robert

You have to declare your method in the subclass.

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

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