虚拟函数的实现可以放在头文件中吗? [英] Can the implementation of a virtual function be put in the header file

查看:131
本文介绍了虚拟函数的实现可以放在头文件中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,如果我们在头文件中放入一个非虚拟成员函数的实现,该函数将被内联。如果我们将头部文件中的虚拟成员函数的实现放在那里呢?我想这与把它放在cpp文件中是一样的,因为内联和多态不能一起工作。我对此有何看法?

解决方案

将头文件中的方法的实现放在内联中。把它放在类声明中。



这里重要的是,声明一个内联函数只是编译器的一个信息,它确实不一定会使该函数内联



大多数情况下,编译器会忽略这一点,并且该方法不会被内联。 b
$ b

虽然可以使用内联虚方法,如c ++ faq所述( http://www.parashift.com/c++-faq-lite/inline-virtuals.html ):
内联虚拟呼叫的唯一时间可以当编译器知道作为虚拟函数调用目标的对象的精确类时,这种情况只有在编译器具有实际对象而不是对象的指针或引用时才会发生,也就是说,一个局部对象,一个全局/静态对象,或一个完全包含在一个组合内的对象。



在shor t,只有当你不使用动态链接解析(我们可以说,当我们不使用虚拟)时,编译器才会内联虚拟方法。


usually if we put an implementation of a non-virtual member function in the header file that function would be inlined. how about if we put the implementation of a virtual member function in the header file? I guess it would be the same as putting it in the cpp file because inlining and polymorphism do not work together. Am I right on this?

解决方案

Putting the implementation of a method in the header file doesn't make it inline. Putting it in the class declaration does. I'll assume that's what you meant from now on.

What is important here is that declaring a function inline is only an information to the compiler, it does not necessarily make that function inline

Most of the time, the compiler will just ignore this and the method won't be inlined.

It's possible to have a virtual method inline though, as stated in the c++ faq (http://www.parashift.com/c++-faq-lite/inline-virtuals.html) : "The only time an inline virtual call can be inlined is when the compiler knows the "exact class" of the object which is the target of the virtual function call. This can happen only when the compiler has an actual object rather than a pointer or reference to an object. I.e., either with a local object, a global/static object, or a fully contained object inside a composite."

In short, the compiler will inline a virtual method only if you don't use dynamic link resolution (we could say, "when we don't use the virtual").

这篇关于虚拟函数的实现可以放在头文件中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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