#include <iostream>
class Person {
//将全局函数的声明放置到类内,并在其前面加上friend关键字
friend void print(const Person &p);
//友元类
friend class Father;
public:
Person():m_age(0){};
Person& add(int a){
m_age = m_age + a;
return *this;
}
private:
void print() {
std::cout << "age = " << m_age << std::endl;
}
private:
int m_age;
};
//虽然我是Person类外的一个函数,但是我的权限大,我要访问你的私有成员m_age
//friend void print(const Person &p);
void print(const Person &p) {
std::cout << "age = " << p.m_age << std::endl;
}
class Father {
public:
void print(Person &p) {
//friend class Father;
//因为是你爸,所以可以可以调用你的private print()
p.print();
}
private:
Person *p;
};
int main() {
Person p;
p.add(1).add(2).add(3);
print(p);
Father f;
f.print(p);
return 0;
}
4. 注意事项: