friend 类和函数
friend 类
#include <iostream>
class FriendClass {
private:
int private_data;
// this means Other is my friend,
// please let him have access to my private memeber
friend class Other;
};
class Other {
public:
FriendClass clz;
Other() { clz.private_data = 2; }
void Print() { std::cout << "PRIVATE: " << clz.private_data; }
void RetrieveData();
};
int main() {
Other other;
other.Print();
return 0;
}
friend 函数
#include <iostream>
class FriendClass;
class Another {
public:
void member_function(const FriendClass &clz);
};
class FriendClass {
public:
FriendClass(int private_data) : private_data(private_data) {}
// please let him have access to my private memeber
friend void friend_function(const FriendClass &clz);
friend void Another::member_function(const FriendClass &clz);
private:
int private_data;
};
void friend_function(const FriendClass &clz) {
std::cout << clz.private_data << '\n';
}
// friend function definition
void Another::member_function(const FriendClass &clz) {
std::cout << "Private Variable: " << clz.private_data << std::endl;
}
int main() {
friend_function(2);
Another another;
another.member_function(2);
return 0;
}
- 友元类和函数具有对类 private 和 protected 成员的访问权限。
- friend 函数中,friend 标识符位于函数的声明式中,而非定义中。
- friend 函数可以在 private, public or protected 中声明。
违反私有性,建议仅在运算符重载时使用。