类中的内联函数成员 [英] inline function members inside a class
问题描述
我知道,当函数定义的性能较小并且可以节省编译时间时,将函数(普通函数而不是类内部的方法)声明为内联是一种好习惯.但是类中的内联方法如何 我不理解类内联方法的概念吗?如何定义它们以及它们如何工作.
I know that declaring a function (normal function not a method inside a class) as inline is a good practice when the function definition is small for performance and it save time for the compilation. But how about inline methods inside a class I don't understand the concept of inline methods inside a class? How to define them and how they work.
推荐答案
但是类中的内联方法如何?
but how about inline methods inside a class ?
内联函数的两种语法(使用显式的inline
并在类定义中定义成员函数)仅提供有关编译器内联的提示.从性能的角度来看,它们是相等的.
Both syntaxes for inlining functions (using explicit inline
and defining member-function inside class definition) provides only hint about inlining for compiler. From performance point of view, they are equal.
在类声明中定义成员函数的情况下,后者的可读性应该是您主要关心的问题:乱码类接口带有多行实现细节确实很麻烦.因此,如果您的成员函数包含多个语句,请避免这样做:return stuff
或简单转发应该可以,但通常不超过该语句.
In case of defining a member-function inside a class declaration, the readability of the latter should be of your main concern: it really hurts to litter class interface with multiple line of implementation details. So avoid doing that if your member-function is more than one statement: return stuff
or simple forwarding should be OK, but usually no more than that.
class MyClass
{
public:
int f() const { return m_i; }
int g() const;
private:
int m_i;
};
inline int MyClass::g() const
{
return m_i;
}
// both member-functions behave equally (except for naming)
这篇关于类中的内联函数成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!