search

Home  >  Q&A  >  body text

c++ - 内联与虚函数

#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不是要在编译时就展开吗?

伊谢尔伦伊谢尔伦2772 days ago367

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:55:32

    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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:55:32

    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.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 14:55:32

    Inline is not expanded at compile time, but at link time. Macros are expanded during preprocessing.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 14:55:32

    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.

    reply
    0
  • Cancelreply