首页 > 技术文章 > 友元

leishenwudi 2020-09-25 17:07 原文

友元是为了让

全局函数作友元

#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
    int age;
private:
    int height;
public:
    Student(int age1,int height1){
        age = age1;
        height = height1;
    }
};
void printHeight(Student &one) 
{
    cout<<one.height<<endl; //这里明显访问不到
}
int main(){
    system("chcp 65001");
    Student stu1(13,135);
    system("pause");
    return 0;
}

访问不到私有属性,只有用友元

#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
    friend void printHeight(Student &one);//加了这行代码
    int age;
private:
    int height;
public:
    Student(int age1,int height1){
        age = age1;
        height = height1;
    }
};
void printHeight(Student &one) 
{
    cout<<one.height<<endl;
}
int main(){
    system("chcp 65001");
    Student stu1(13,135);
    printHeight(stu1);
    system("pause");
    return 0;
}

成功访问

友元类

当一个 类作为另一个类的成员时,如果要访问作为成员对象的私有成员,可以在作为成员对象的类定义中加上

成员函数作友元

只需要在需要被访问私有属性的类定义中加入对成员函数的friend声明即可

推荐阅读