简体   繁体   English

派生类之外的纯虚函数定义

[英]Pure virtual function definition outside derived class

I have abstract base class and derived class in header file. 我在头文件中有抽象基类和派生类。 Is it possible to have definition of pure virtual function outside the derived class? 是否可以在派生类之外定义纯虚函数?

For example: 例如:

//file .h
class Baseclass
{
public:
    virtual int vfunc() = o;
   //assume Ctor and Dctor
};
class Derivedclass : public Baseclass
{
public:
    int vfunc();
    //assume Ctor and Dctor
};

Now in the cpp file: 现在在cpp文件中:

#include <file.h>
int Derivedclass :: vfunc()
{
    // Body of the function
}

Is the above method correct/possible? 上述方法是否正确/可行?

This is not only possible, it's standard practice. 这不仅是可能的,而且是标准做法。 The only time you have to worry about putting function definitions into the header is with templates. 您唯一需要担心将函数定义放入标题中的方法是使用模板。

Yes it is possible. 对的,这是可能的。 You can define them outside your class, if that is what at all you want to ask. 您可以在课堂外定义它们,如果这是您想要询问的内容。

Is it possible to have definition of pure virtual function outside the derived class? 是否可以在派生类之外定义纯虚函数?

The function is not pure virtual in the derived class, it's only pure virtual in the base class. 该函数在派生类中不是纯虚函数,它只是基类中的纯虚函数。

The derived class overrides the function and does not have a pure-specifier (the =0 bit after the function declarator) so DerivedClass::vfunc() is not pure virtual, and therefore must have a definition somewhere if it's used in the program. 派生类会覆盖该函数,并且没有纯指定符(函数声明DerivedClass::vfunc()后面的=0位),因此DerivedClass::vfunc()不是纯虚拟的,因此如果在程序中使用它,则必须在某处具有定义。 Defining it in a separate file from the header is perfectly normal. 将其定义在与标题不同的文件中是完全正常的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM