在类中定义一个成员函数而不是在C ++外部? [英] Defining a member function inside the class instead of outside in C++?

查看:110
本文介绍了在类中定义一个成员函数而不是在C ++外部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过在头文件中的类中写入成员函数的定义如下,我被告知编译器将它视为一个内联函数 - 因此,在程序中遇到此函数的任何地方,它会进入完整函数的主体,而不是跳转到函数驻留在内存中的一个位置。这是真的吗?

  class myClass 
{
public:
void Fun1()
{
//在此执行
}
}



$ b



我被告知编译器将其视为内联函数。 p>正确的。这意味着它可以在多个翻译单元中定义,如果您想在标题中定义它并在程序中多次包含该标题,那么这是必需的。


因此,在程序中遇到此函数的任何地方,它都会每次进入函数的完整主体,而不是跳转到函数驻留在内存中的一个位置。


不,这不是 inline 在函数定义的上下文中的含义。这就是函数调用内联的优化,如果编译器认为它会改进代码,它可以应用于任何调用。



这两个概念松散地相关:编译器处理一次只有一个翻译单元只能将优化应用于当前单元中定义的功能,因此他们需要有多个定义才能在多个单元中对其进行优化。


By writing the definition of a member function inside the class in the header file as follows, I was told that compiler treats this as an inline function - hence , anywhere it encounters this function being called in the program , it enters the complete body of the function every time instead of jumping to the one location where the function resides in memory. Is this true?

class myClass
{
    public:
       void Fun1()
       {
         //implemented here
       }
}

解决方案

I was told that compiler treats this as an inline function

Correct. That means that it's allowed to be defined in more than one translation unit, which is necessary if you want to define it in a header and include that header more than once in your program.

Hence , anywhere it encounters this function being called in the program , it enters the complete body of the function every time instead of jumping to the one location where the function resides in memory

No, that's not what inline means in the context of a function definition. That's the optimisation of function call inlining, which the compiler can apply to any call if it thinks it will improve the code.

The two concepts are loosely related: compilers which process a single translation unit at a time will only be able to apply the optimisation to functions defined in the current unit, so they'll need to have multiple definitions to be able to optimise them in more than one unit.

这篇关于在类中定义一个成员函数而不是在C ++外部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆