四.友元
創(chuàng)新互聯(lián)建站專注于溫嶺企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站設(shè)計(jì),商城建設(shè)。溫嶺網(wǎng)站建設(shè)公司,為溫嶺等地區(qū)提供建站服務(wù)。全流程按需制作,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)建站專業(yè)和態(tài)度為您提供的服務(wù)在程序里,有些私有屬性 也想讓類外特殊的一些函數(shù)或者類進(jìn)行訪問(wèn),就需要用到友元的技術(shù)
友元的目的就是讓一個(gè)函數(shù)或者類 訪問(wèn)另一個(gè)類中私有成員
友元的關(guān)鍵字為? =friend=
友元的三種實(shí)現(xiàn)
* 全局函數(shù)做友元
* 類做友元
* 成員函數(shù)做友元
1.全局函數(shù)做友元
#include
using namespace std;
class Student
{
private:
static int age;
public:
static int id;
Student()
{
age = 0;
id = 1;
}
};
void visit(Student *student)
{
cout<< student->id<< endl;
cout<< student->age<< endl;
}
int main()
{
Student student01;
visit(&student01);
return 0;
}
#include
using namespace std;
class Student
{
friend void visit(Student* student);
private:
int age;
public:
int id;
Student()
{
age = 0;
id = 1;
}
};
void visit(Student *student)
{
cout<< student->id<< endl;
cout<< student->age<< endl;
}
int main()
{
Student student01;
visit(&student01);
return 0;
}
2.類做有元
#include
using namespace std;
class Student
{
friend class Visit;
private:
int age;
public:
int id;
Student()
{
age = 0;
id = 1;
}
};
class Visit
{
private:
Student* student;
public:
void visit()
{
cout<< student->id<< endl;
cout<< student->age<< endl;
}
Visit()
{
student = new Student;
}
};
int main()
{
Visit visit01;
visit01.visit();
return 0;
}
3.成員函數(shù)做友元
#include
using namespace std;
class Student;
class Visit
{
private:
Student* student;
public:
Visit();
void visit02();
};
class Student
{
friend void Visit::visit02();
private:
int age;
public:
int id;
Student()
{
age = 0;
id = 1;
}
};
void Visit::visit02()
{
cout<< student->id<< endl;
cout<< student->age<< endl;
}
Visit::Visit()
{
student = new Student;
}
int main()
{
Visit visit01;
visit01.visit02();
return 0;
}
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購(gòu),新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧