虚拟函数的实现可以放在头文件中吗? [英] Can the implementation of a virtual function be put in the header file
问题描述
将头文件中的方法的实现放在内联中。把它放在类声明中。
这里重要的是,声明一个内联函数只是编译器的一个信息,它确实不一定会使该函数内联
大多数情况下,编译器会忽略这一点,并且该方法不会被内联。 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屋!