.cpp 文件中的 C++ 内联成员函数

2021-12-07 00:00:00 function inline c++ member

我知道根据定义内联成员函数应该进入标题.但是如果无法将函数的实现放入头文件中怎么办?让我们来看看这种情况:

I know that inline member functions by definition should go into the header. But what if it's not possible to put the implementation of the function into the header? Let's take this situation:

文件 A.h

#pragma once
#include "B.h"

class A{
    B b;
};

文件 B.h

#pragma once

class A; //forward declaration

class B{
    inline A getA();
};

由于循环包含,我必须将getA的实现放入

Due to the circular include I have to put the implementation of getA into

B.cpp

#include "B.h"
#include "A.h"

inline A B::getA(){
    return A();
}

编译器会内联 getA 吗?如果是这样,哪个内联关键字是重要的(标题中的一个或 .cpp 文件中的一个)?是否有另一种方法将内联成员函数的定义放入其 .cpp 文件中?

Will the compiler inline getA? If so, which inline keyword is the significant one (the one in the header or the one in the .cpp file)? Is there another way to put the definition of an inline member function into its .cpp file?

推荐答案

引用自 C++ 常见问题:

注意:当务之急是函数的定义(部分在 {...}) 之间放置在头文件,除非函数是仅在单个 .cpp 文件中使用.在特别是,如果你把内联函数定义到 .cpp 文件中然后你从其他一些 .cpp 调用它文件,你会得到一个未解决的来自链接器的外部"错误.

Note: It's imperative that the function's definition (the part between the {...}) be placed in a header file, unless the function is used only in a single .cpp file. In particular, if you put the inline function's definition into a .cpp file and you call it from some other .cpp file, you'll get an "unresolved external" error from the linker.

编译器需要查看内联函数的定义,只要它发现任何使用内联函数的地方.如果将内联函数放在头文件中,这通常是可能的.

The compiler need to see the definition of the inline function whenever it finds any use of that inline function. That is typically possible if the inline function is placed in a header file.

编译器会内联 getA 吗?

Will the compiler inline getA?

否,除非 getA() 的使用在 B.cpp 本身中.

No, except when the the use of getA() is in B.cpp itself.

如果是这样,哪个内联关键字是重要的(在标题中的一个或在 cpp 中的一个)?

If so, which inline keyword is the significant one (the one in the header or the one in the cpp)?

最佳实践:仅在定义在类体之外.

Best practice: only in the definition outside the class body.

还有其他方法可以将内联成员函数的定义放入它的 cpp 文件中吗?

Is there another way to put the definition of an inline member function into it's cpp file?

不,至少我不知道.

相关文章