#include <iostream>
using namespace std;
class A
{
virtual void func()
{
cout << "zz\n";
}
virtual void prin();
};
inline void A::prin()
{
cout << "h";
}
int main()
{
return 0;
}
为什么inline
可以修饰virtual
函数呢?虚函数调用不是要在运行时才能确定吗?而inline
不是要在编译时就展开吗?
has a very limited effect. The compiler usually ignores the inline modification. Of course, there are exceptions:
inline virtual
will only work when the object type is determined at compile time, that is, the caller that calls thisinline virtual
cannot It is a reference or pointer, which can be a local variable, static variable, or global variable. At this time, the compiler may optimize this virtual function into a normal member function and inline it, but whether to do so depends on the compiler and cannot be guaranteed.Theoretically speaking, the two should not coexist. But unlike
virtual
,inline
is just the optimization suggestion of the compiler. The compiler may not necessarily adoptinline
and this建议
, so the coexistence of the two is allowed in writing, but in actual compilation,inline
It will not expand.In addition, I have seen some information saying that the
virtual
function may also be determined at compile time, so thatinline
can be implemented. However, these are all Compiler Dependent, so we cannot say for sure.Inline is not expanded at compile time, but at link time. Macros are expanded during preprocessing.
My suggestion is to ignore the
inline
keyword in most cases, because most C++ compilers are intelligent handlers of function inlining, and member functions with hundreds of lines can be directly Inlining, and as mentioned aboveinline
is only a suggestion to the compiler and does not play an absolute role.