虚拟函数本质上应该有一个定义 [英] Should a virtual function essentially have a definition

查看:241
本文介绍了虚拟函数本质上应该有一个定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个虚拟函数的定义非常重要吗?

Is it essential to have a definition for a virtual function?

请考虑下面的示例程序:

Consider this sample program below:

#include <iostream>

using namespace std;

class base
{
   public:
      void virtual virtualfunc();
};

class derived : public base
{
   public:
   void virtualfunc()
   {
      cout << "vf in derived class\n";
   }
};

int main()
{
   derived d;
   return 0;
}

这会产生链接错误:


在函数中base :: base()'::未定义引用 vtable为base'

In function base::base()':: undefined reference tovtable for base'

我没有基类中虚函数的定义。为什么会出现此错误,即使我没有明确调用虚函数?

I do not have the definition for the virtual function in base class. Why is this error occurring even-though, i have not explicitly invoked the virtual function?

EDIT

我发现的有趣的事情是,如果我不实例化类派生的对象,链接错误不再存在?为什么是这样?

The interesting thing which i find is that if i do not instantiate an object of class derived, the link-error is no longer there? Why is this? What has instantiation got to do with the above link-error?

推荐答案

ISO C ++标准规定了类的所有虚方法

The ISO C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined.

参考:

:10.3虚函数[class.virtual]


在类中声明的虚函数应被定义或声明为纯10.4),或两者;但不需要诊断(3.2)。

A virtual function declared in a class shall be defined, or declared pure (10.4) in that class, or both; but no diagnostic is required (3.2).

所以,你应该使函数纯虚函数或提供一个定义。

So either you should make the function pure virtual or provide a definition for it.

如果您使用gcc,如果您不遵守此标准规范,您可能会遇到一些奇怪的错误。 gcc faq 也可以:

If you are using gcc, You might get some weird errors if you fail to follow this standard specification. The gcc faq doccuments it as well:


ISO C ++标准规定必须定义非纯虚拟类的所有虚方法,但不需要对违反此规则的任何诊断 [class.virtual] / 8 。基于这个假设,GCC将仅在定义其第一个这样的非内联方法的翻译单元中发出隐式定义的构造函数,赋值运算符,析构函数和虚表。

The ISO C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined, but does not require any diagnostic for violations of this rule [class.virtual]/8. Based on this assumption, GCC will only emit the implicitly defined constructors, the assignment operator, the destructor and the virtual table of a class in the translation unit that defines its first such non-inline method.

因此,如果你没有定义这个特定的方法,链接器可能会抱怨缺少明显不相关的符号的定义。不幸的是,为了改进此错误消息,可能需要更改链接器,但这不能总是完成。

Therefore, if you fail to define this particular method, the linker may complain about the lack of definitions for apparently unrelated symbols. Unfortunately, in order to improve this error message, it might be necessary to change the linker, and this can't always be done.

解决方案是确保所有定义不纯的虚拟方法。注意,即使声明为纯虚拟 [class.dtor] / 7

The solution is to ensure that all virtual methods that are not pure are defined. Note that a destructor must be defined even if it is declared pure-virtual [class.dtor]/7.

这篇关于虚拟函数本质上应该有一个定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆