我很新的C++,當我想了解的朋友的功能,我從friend description on Cppreference看到:非會員朋友的功能始終是內嵌
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
}
};
這是否意味着所有的友元函數總是要內嵌?換句話說,朋友功能必須在課堂上完全定義嗎?
不過,我也發現那裏的友元函數定義在類外從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;
}
我真的這場衝突混淆一個實例。我的理解內聯錯了嗎? 「a nonmember friend function defined inside the class is automatically inline」是什麼意思?
。在類中定義的朋友函數*是內聯的。這並不意味着所有的朋友函數都是內聯的。你的第二個例子清楚地顯示了在課堂外定義的朋友函數。它不是內聯的。 – AnT
您引用cppreference的語法2,然後問「這是否意味着所有的朋友函數都必須是內聯的?」否:在前面的語法1中給出了一個反例。 –