Nonmember friend function is always inline

孤街醉人 提交于 2021-02-08 12:51:15

问题


I am very new to C++, and when I am trying to learn the friend function, I saw from friend description on Cppreference that:

2) (only allowed in non-local class definitions) Defines a non-member function, and makes it a friend of this class at the same time. Such non-member function is always inline.

class X {
  int a;
  friend void friend_set(X& p, int i) {
    p.a = i; // this is a non-member function
  }
  public:
  void member_set(int i) {
      a = i; // this is a member function
  }
};

Does this mean that all friend functions always have to be inline? In another word, must the friend functions be defined completely inside the class?

However, I also found an instance where the friend function is defined outside the class from Cplusplus

// friend functions
#include <iostream>
using namespace std;
class Rectangle {
  int width, height;
  public:
    Rectangle() {}
    Rectangle (int x, int y) : width(x), height(y) {}
    int area() {return width * height;}
    friend Rectangle duplicate (const Rectangle&);
};
Rectangle duplicate (const Rectangle& param)
{
  Rectangle res;
  res.width = param.width*2;
  res.height = param.height*2;
  return res;
}

I am really confused by this conflict. Is my understanding of inline wrong? What does it mean by "a nonmember friend function defined inside the class is automatically inline"?


回答1:


any function defined inside a class (member or non-member friend) is always implicitly inline. That's because class definitions are generally in header files, and you don't want any non-inline function definitions in a header file (having a non-inline function in a header leads to multiple definitions if the header is #included in more than one source file).

If you want a function to be non-inline, you need to define it outside of a class definition. If its a member or friend you still need to declare it inside the class, since members and friends must be declared in the class. You just don't want it defined in the class.

This all gets into the difference between a definition and a declaration in C++ -- they are two distinct things, though every definition is also implicitly a declaration, not every declaration is a definition. As a result, when the spec says 'declaration' it often means 'declaration that is not also a definition'



来源:https://stackoverflow.com/questions/40793784/nonmember-friend-function-is-always-inline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!