c++友元详解

一、友元的概述

  1. 友元依靠关键字friend进行声明。
  2. friend关键字只出现在声明处 。
  3. 其他类、类成员函数、全局函数都可声明为友元 友元函数。
  4. 友元不是类的成员,不带this指针 。
  5. 友元函数可访问对象任意成员属性,包括私有属性。

二、全局函数做友元

全局函数作友元的方法:定义一个全局函数,将其在类内声明(前面加上关键字friend),此时该全局函数就成了这个类的友元,可以访问类内的全部属性

#include <iostream>
#include <string>

using namespace std;

class student {

friend void  setnum(student &stu);
public:
    int age;

private:
    int num;
};

void setnum(student &stu)
{
    stu.num =10;
    cout<<"私有属性num的值为:"<<stu.num<<endl;
}


void test1()
{
    student stu_1;
    setnum(stu_1);
 
}



int main()
{
    test1();            
    system("pause");    
}

在这里插入图片描述

三、类作友元

类作友元的方法:定义一个类,将其在另一个类内声明(前面加上关键字friend),此时前一个类就成了后一个类的友元,可以访问类内的全部属性。

#include <iostream>
#include <string>

using namespace std;

class student {

friend class teacher;
friend void test1();
public:
    int age;

private:
    int score;
};

class teacher{
public:
    void setscore(student &stu)
    {
        stu.score=100;
    }
};



void test1()
{
    student stu_1;
    teacher tea_1;
    tea_1.setscore(stu_1);
        cout << "老师类做友元修改学生的私有属性score为:"<<stu_1.score<<endl;

 
}



int main()
{
    test1();            
    system("pause");    
}

在这里插入图片描述

四、使用成员函数作友元

使用成员函数作友元方法和前两个大同小异,这里的关键是由类的定义顺序造成的前一个类的成员函数无法访问后一个类的属性。这里采用的方法是提前声明后面的类。对于成员函数无法访问到后一个类的成员,可以先将该成员函数声明,再在所有类定义完之后再进行定义。

#include <iostream>
#include <string>

using namespace std;

class student;

class teacher{
public:
    teacher();
    student *stu_1;

    ~teacher()
    {
        delete stu_1;
    }

};

class student {
    friend  teacher::teacher();
public:
    int age;

    ~student();

private:
    int score;
};

teacher::teacher()
{
    stu_1=new student;
    stu_1->score=100;
    cout<<"stu_1的私有属性score为:"<<stu_1->score<<endl;
}



void test1()
{
    teacher tea_1;
    
    
}



int main()
{
    test1();            
    system("pause");    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值