非会员的朋友功能始终是内联的 [英] Nonmember friend function is always inline

查看:74
本文介绍了非会员的朋友功能始终是内联的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++还是很陌生,当我尝试学习Friends函数时,我从

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)(仅在非本地类定义中允许)定义一个非成员函数,并使其同时成为该类的朋友.此类非成员功能始终是内联.

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?

但是,我还找到了一个实例,该实例在 Cplusplus的类之外定义了朋友函数.

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"?

推荐答案

任何函数始终是隐式内联的.这是因为类定义通常在头文件中,并且您不希望头文件中有任何非内联函数定义(如果头中包含#多个头,则头中具有非内联函数会导致多个定义源文件).

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.

这一切都进入了C ++中的定义声明之间的区别–它们是两个截然不同的东西,尽管每个定义也隐式地是一个声明,而不是每个声明是一个定义.结果,当规范说声明"时,通常意味着声明也不是定义"

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'

这篇关于非会员的朋友功能始终是内联的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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