友元:申明一个外部成员(函数、类)可以访问当前类的所有成员
形象理解:申明一个外部成员(函数、类)是当前类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();
}