.cpp文件中的C ++内联成员函数 [英] C++ inline member function in .cpp file

查看:252
本文介绍了.cpp文件中的C ++内联成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道内联成员函数按照定义应该进入标题。但是如果不可能把函数的实现放到头中呢?让我们来看这种情况:

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:

文件啊

#pragma once
#include "B.h"

class A{
    B b;
};

文件Bh

#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 ?如果是这样,哪个inline关键字是有效的一个(标题中的一个或.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?

推荐答案

http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.9\"> C++常见问题:

Quoting from C++ FAQ:


注意:必须将
函数的定义({...}之间的
部分)放在
头文件中,除非函数是
仅在单个.cpp文件中使用。在
特别的,如果你把内联
函数的定义放入一个.cpp文件
,并从其他一些.cpp
文件调用,你会得到一个未解决的
external错误。

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() .cpp本身。

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


如果是这样,哪个inline关键字是有效的一个(标题中的一个还是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?

不,至少我不知道。

这篇关于.cpp文件中的C ++内联成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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