c++ - 内联与虚函数
伊谢尔伦
伊谢尔伦 2017-04-17 14:53:32
0
4
365
#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不是要在编译时就展开吗?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(4)
洪涛

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 this inline 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.

Peter_Zhu

Theoretically speaking, the two should not coexist. But unlike virtual, inline is just the optimization suggestion of the compiler. The compiler may not necessarily adopt inline and this 建议, so the coexistence of the two is allowed in writing, but in actual compilation, inlineIt will not expand.
In addition, I have seen some information saying that the virtual function may also be determined at compile time, so that inline 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 above inline is only a suggestion to the compiler and does not play an absolute role.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template