1、友元关系不可传递
2、通过友元可以访问类中的私有变量
3、友元破坏了类的封装,小心使用
友元函数
1、友元全局函数
#include <iostream>
using namespace std;
class Person{
friend void getAge(Person& person);
public:
string name;
private:
int age = 10;
};
void getAge(Person& person){
cout<<"age:"<<person.age<<endl;
}
int main(){
Person person;
getAge(person);
return 0;
}
2、友元成员函数
这个我没做出来。。。可能是编译器的问题。大体思路与友元全局函数一样,只不过把友元函数放在了一个类里面
友元类
#include <iostream>
using namespace std;
class Friend;//declaration
class Person{
friend Friend;
public:
string name;
private:
int age = 10;
};
class Friend{
public:
void getAge(){
cout<<"age:"<<person.age<<endl;
}
void setAge(int x){
person.age = x;
}
private:
Person person;
};
int main(){
Person person;
Friend aFriend;
aFriend.setAge(15);
aFriend.getAge();
return 0;
}