C++之友元

友元:申明一个外部成员(函数、类)可以访问当前类的所有成员
形象理解:申明一个外部成员(函数、类)是当前类A的朋友,作为A类的朋友可以访问A类中的所有信息
注意:friend只是申明的一种关系,并非函数、类的申明,并且在friend时,函数、类可被访问
友元:友元函数,友元类,友元成员函数
有一个问题:友元能提高运行效率吗?截止目前为止查找的所有资料中都不能证明这一观点。你们又是怎么觉得呢?


友元函数

#include <QCoreApplication>
#include <iostream>
#include <string>
#include <sys/types.h>

using namespace std;

class Student{
private:
    int id;
    string *name;
    friend void test(Student &stu);//friend一个函数,在全局定义这个函数
public:
    Student(int id_t, const char *name_t){
        id = id_t;
        name = new string(name_t);
    }
    ~Student(){
        delete name;
    }
};

void test(Student &stu){
    cout << stu.id << "," << *stu.name << endl;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Student stu(1, "xiaoli");
    test(stu);
    return a.exec();
}

友元类

#include <QCoreApplication>
#include <iostream>
#include <string>
#include <sys/types.h>

using namespace std;

class Student{
private:
    int id;
    string *name;
    friend class B;//friend B类,在Student类外定义一个B类,在B类中所有成员函数中都可访问Student类中所有成员
public:
    Student(int id_t, const char *name_t){
        id = id_t;
        name = new string(name_t);
    }
    ~Student(){
        delete name;
    }
};

class B{
public:
    void test(Student &stu){
        cout << stu.id << "," << *stu.name << endl;
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Student stu(1, "xiaoli");
    B b;
    b.test(stu);
    return a.exec();
}

友元成员函数

#include <QCoreApplication>
#include <iostream>
#include <string>
#include <sys/types.h>

using namespace std;

class Student;

class B{
public:
    void test(Student &stu);
};

class Student{
private:
    int id;
    string *name;
    friend void B::test(Student &stu);//friend B类的成员函数test,在B类中的test函数才能够访问Student类中所有的成员
public:
    Student(int id_t, const char *name_t){
        id = id_t;
        name = new string(name_t);
    }
    ~Student(){
        delete name;
    }
};

void B::test(Student &stu){
    cout << stu.id << "," << *stu.name << endl;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Student stu(1, "xiaoli");
    B b;
    b.test(stu);
    return a.exec();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值