类与对象之友元


​ 在程序里,有些所有属性也想让类外特殊的一些函数进行访问,就需要用到友元技术。友元的目的就是让一个函数或类访问另一个类中私有成员。友元的关键字就是friend.

友元的三种实现:

  • 全局变量做友元
  • 类做友元
  • 成员函数做友元

简单实例

全局变量做友元:

#include<iostream>
#include<string>
using namespace std;
class Building
{
friend void goodgay(Building* b);
string bedroom;
public:
Building()
{
livingroom = "客厅";
bedroom = "卧室";
}
string livingroom;
};
void goodgay(Building* b)
{
cout << "好基友正在访问......" << b->livingroom << endl;
//如果直接改成卧室会报错
//但如果把此全局函数复制到类的首部并加上friend则可以访问卧室
cout << "好基友正在访问......" << b->bedroom << endl;
}
void test01()
{
Building b;
goodgay(&b);
}
int main()
{
test01();
return 0;
}
好基友正在访问......客厅
好基友正在访问......卧室

类做友元:

#include <iostream>
#include <string>

using namespace std;
class Building
{
friend class Goodgay;
string bedroom;
public:
Building();

string livingroom;
};
class Goodgay
{
public:
Building* b;
void visit();
Goodgay();

};
Building::Building()
{
livingroom = "客厅";
bedroom = "卧室";
}

void Goodgay::visit()
{
cout << "好基友正在访问......" << b->livingroom << endl;
cout << "好基友正在访问......" << b->bedroom << endl;
}

Goodgay::Goodgay()
{
//创建新对象
b = new Building;
}
void test01()
{
Goodgay gg;
gg.visit();
}
int main()
{
test01();
return 0;
}
好基友正在访问......客厅
好基友正在访问......卧室

成员函数做友元:

#include <iostream>
#include <string>

using namespace std;

class Building
{
friend void Goodgay::visit(); // 友元声明
private:
string bedroom;
public:
Building();

string livingroom;
};

class Goodgay
{
public:
Building* b;
void visit();
Goodgay();
~Goodgay(); // 析构函数,用来释放动态分配的内存
};
Building::Building()
{
livingroom = "客厅";
bedroom = "卧室";
}

void Goodgay::visit()
{
cout << "好基友正在访问......" << b->livingroom << endl;
cout << "好基友正在访问......" << b->bedroom << endl; // 正确访问私有成员
}

Goodgay::Goodgay()
{
b = new Building;
}

Goodgay::~Goodgay() // 析构函数,用来释放动态分配的内存
{
delete b;
b = nullptr;
}

void test01()
{
Goodgay gg;
gg.visit();
}

int main()
{
test01();
return 0;
}
好基友正在访问......客厅
好基友正在访问......卧室

课本实例

友元函数:
#include<iostream>
#include<string>
using namespace std;
class Croster
{
friend bool Equal(Croster&, Croster&);
string name;
int Math;
const double Score;//定义学分常数据成员
double GPA;//绩点
public:
Croster(string na = "undef", int m = 100, double s = 3);
double GetGPA() const;//常数据成员函数返回绩点
};
#include "l4_08.h"
Croster::Croster(string na, int m, double s) :name(na), Math(m), Score(s)
{
GPA = Math / 100.0 * Score;
}
double Croster::GetGPA() const
{
return GPA;
}


bool Equal(Croster &A, Croster &B)
{
if (A.GPA==B.GPA)
return true;
else
return false;
}
#include "l4_08.h"
int main()
{
Croster stuA("李梅", 96, 3), stuB("孙立", 98, 3);
if (Equal(stuA, stuB))
cout << "GPA is same\n";
else
cout << "GPA is different\n";
return 0;
}
其他的大同小异,就不赘述了…………..

Author: T1g3r
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source T1g3r !
评论
  TOC