About Why Inline Member Function Should Defined in The Header File

About why inline member function should defined in the header file.

It is legal to specify inline on both the declaration and the definition. But the keyword inline must be placed with the function definition body to make the function inline. Just putting inline in front of function declaration has no effect.

So inline member functions should be declared and defined in the same header. In other words, the inline function should (not must) be placed in the header file instead of the cpp file. An identical definition for the function must exist in every translation unit that uses that line function because one definition rule for inline functions. Otherwise, the compiler will report an error(LINK2019 unsolved external symbol) because the compiler must be able to see the same function define for every call. So. .yes, if you use an inline function in only a cpp file and no others will call it, you can put function define in that cpp file and then successfully pass compilation. If you accidentally call it in another file, the compiler will throw an error.

And the same time, inline member function declared outside the class in the header must be marked inline because otherwise, every translation unit which includes the header will contain a definition of the function, and the linker will complain about multiple definitions. As mentioned above, one definition rule.

posted @ 2019-01-18 15:13  威化饼干  阅读(98)  评论(0编辑  收藏  举报