友元函数的三种情况
1)全局函数做友元
2)类做友元
3)成员函数做友元
1)全局函数做友元
#include<iostream>
using namespace std;
class A{
private:
int n1;
public:
};
void fun1(A* a){
cout<<a->n1<<endl; //错误 私有成员无法类外访问
}
int main(){
return 0;
}
#include<iostream>
using namespace std;
class A{
private:
int n1;
public:
friend void fun1(A* a); //fun1成了A的友元函数,可访问私有成员
};
void fun1(A* a){
cout<<a->n1<<endl;
}
int main(){
return 0;
}
2)类做友元
#include<iostream>
using namespace std;
class A{
private:
int n1;
};
class B{
private:
int n1;
public:
void show(A* a){
cout<<a->n1<<endl; //报错 无法访问A类的私有成员
}
};
int main(){
return 0;
}
#include<iostream>
using namespace std;
class A{
friend class B; // B类成了A类的友元类
private:
int n1;
};
class B{
private:
int n1;
public:
void show(A* a){
cout<<a->n1<<endl; //正确
}
};
int main(){
return 0;
}
3)成员函数做友元
#include<iostream>
using namespace std;
class A;
class B{
public:
B();
A* a;
void show();
};
class A{
//声明 B的成员函数show()为A类的友元函数,可访问A自身的私有成员
friend void B::show();
public:
A(){
n1 = 100;
};
public:
int n1;
};
B::B(){
a = new A;
}
void B::show(){
cout<<a->n1<<endl; // B的成员函数可以访问A的私有成员 n1
}
int main(){
return 0;
}