我是 C++ 的新手,当我尝试学习 friend 函数时,我从 friend description on Cppreference 看到了那:
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
}
};
这是否意味着所有友元函数都必须内联?换句话说,友元函数必须完全在类内部定义吗?
但是,我还发现了一个实例,其中 friend 函数是在 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;
}
我真的被这个冲突搞糊涂了。我对 inline 的理解有误吗? “a nonmember friend function defined inside the class is automatically inline”是什么意思?
最佳答案
任何 在类(成员或非成员 friend )中定义的函数总是隐式内联的。那是因为类定义通常在头文件中,并且您不希望头文件中有任何非内联函数定义(如果头文件#included 在多个文件中,那么头文件中的非内联函数会导致多个定义源文件)。
如果你希望一个函数是非内联的,你需要在类定义之外定义它。如果它是成员或 friend ,您仍然需要在类中声明它,因为成员和 friend 必须在类中声明。您只是不想在类中定义它。
这一切都涉及到 C++ 中定义和声明之间的区别——它们是两个截然不同的东西,尽管每个定义也隐含地是一个声明,而不是每个声明是一个定义。因此,当规范说“声明”时,它通常意味着“不是定义的声明”
关于c++ - 非成员好友函数总是内联的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40793784/