C ++实现朋友/内联函数 [英] c++ implementing friend/inline functions

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

问题描述

我似乎找不到这个新手问题的答案。如果我有
类//头文件(.h)

I can't seem to find the answer to this newbie question. If I have a class // Header file (.h)

Class X {
public:
  friend bool operator==(const X&, const X&);
  inline size_type rows() const;
};

等...
当我去实现X的.cpp文件时,应该我加入了inline& .cpp文件中函数名称中的朋友。也就是说,我是否应该像下面那样实现我的文件

etc... when I go to implement the .cpp file of X, should I include the words inline & friend in the function names in the .cpp file. ie, should I implement my file similar to the below

// CPP file (.cpp)
#include "X.h"
friend bool operator==(const X&, const X&) {
  //implementation goes here
  //return true/false
}

inline size_type rows() const {
  return r;
}

或者我不应该包括这些内容,例如下面的

or should I not include these i.e. like below

#include "X.h"
bool operator==(const X&, const X&) { ... }

size_type rows() const { ... }


推荐答案

否,您不应该这样做,即第二版是正确的。

No, you shouldn't, i.e. the 2nd version is correct.

friend 仅可用于类定义(其外面没有任何意义),编译器会寻找函数签名来查找在您的类 friend 函数的定义> X 。

friend can only be used within a class definition (it has no meaning outside of it), and the compiler looks for the function signature to find the definition of the friend function declared within your class X.

inline 用于头文件(尽管我想,从技术上讲,也可以在cpp文件中使用它,只是在那里没有意义)。并请注意,仅当您实际上在此处定义函数时, inline 才有意义-如果在cpp文件中单独提供函数定义,则不会起作用。

inline is used in header files (although, I guess, technically it is possible to use it in a cpp file too, just it makes no sense there). And note that inline makes sense only if you actually define the function right there - it can have no effect if you provide the function definition separately, in a cpp file.

内联的意义是暗示编译器可以内嵌相关函数(尽管不能保证-编译器可以自由决定是否内联该功能)。如果内联该函数,则对该函数的任何调用都将替换为该函数主体的副本。实际上,这样做总是为了提高性能,以节省函数调用的成本,但以可能增加程序大小为代价。现在,如果要内联一个函数,我们不仅希望在单个编译单元内,而且希望在各处进行内联。这就是为什么在实现文件中使用 inline 关键字几乎没有意义的原因。

The point of inline is to hint the compiler that the function in question can be inlined (it is no guarantee, though - the compiler is free to decide whether it inlines that function or not). If the function is inlined, any calls to it are replaced by a copy of the function body. This is practically always done for performance benefits, to save the costs of function calls, at the expense of potentially increasing program size. Now, if we want to inline a function, we want it to be inlined all over the place, not only within a single compilation unit; this is why it makes little sense to use the inline keyword inside an implementation file.

这篇关于C ++实现朋友/内联函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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