访问权限
权限从大到小是public>protected>private
public
可以被该类中的函数,子类的函数,其友元函数访问,也可以由,该类的对象访问
protected
可以被该类中的函数,子类的函数,其友元函数访问,但不能被该类的对象访问。
private
只能由该类中的函数,其友元函数访问,不能被其他访问,该类的对象也不能访问。
友元
友元顾名思义是作为朋友的一个成员,他的访问权限比较大,友元可以分为友元类,友元函数,他们可以访问类中的被private修饰的私有成员,友元的修饰符是用friend修饰。
友元全局函数
#include <iostream>
using namespace std;
class person{
friend void visit();只需要在类中声明时添加一个friend修饰符
public:
person(int age){
m_age=age;
}
private:
int m_age;
};
void visit(){
person p1(52);
cout<<"年龄是:"<<p1.m_age<<endl;
}
int main(){
visit();
return 0;
}
友元类
#include <iostream>
using namespace std;
class person{
friend class student;
public:
person(){
m_age=20;
}
private:
int m_age;
};
class student{
public:
void visit(){
cout<<m_p.m_age<<endl;
}
person m_p;
};
int main(){
student s;
s.visit();
return 0;
}
友元成员函数
#include <iostream>
#include <string>
using namespace std;
class person;
class student{
public:
void visit();
person *m_p;
};
class person{
friend void student::visit();
public:
person(){
m_age=20;
}
private:
int m_age;
};
void student::visit(){
m_p=new person;
cout<<m_p->m_age<<endl;
}
int main(){
student s;
s.visit();
return 0;
}