类中友元函数的应用
类中友元函数则是为了访问私有变量,如类B需要访问类A中的私有变量,则代码如下:
example one:
#include "stdafx.h"
#include
using namespace std;
class B; //提前申明类B
class A{
public:
A(){
English=19;
};
void between(B &b); //类B为类A的成员函数
private:
double English;
};
#include
using namespace std;
class B; //提前申明类B
class A{
public:
A(){
English=19;
};
void between(B &b); //类B为类A的成员函数
private:
double English;
};
class B {
public:
B(){Eng_score=0;};
friend void A::between(B &p); //类A为类B的友元函数,此函数可以访问类A中的私有变量,如English
private:
double Eng_score;
};
void A::between(B &p){
p.Eng_score=English; //直接访问English
cout<<"Eng_score="<<p.Eng_score<<endl;
};
int _tmain(int argc, _TCHAR* argv[])
{
A a;
B b;
a.between(b); //引用类B的对象b
while (1);
return 0;
}
public:
B(){Eng_score=0;};
friend void A::between(B &p); //类A为类B的友元函数,此函数可以访问类A中的私有变量,如English
private:
double Eng_score;
};
void A::between(B &p){
p.Eng_score=English; //直接访问English
cout<<"Eng_score="<<p.Eng_score<<endl;
};
int _tmain(int argc, _TCHAR* argv[])
{
A a;
B b;
a.between(b); //引用类B的对象b
while (1);
return 0;
}
example two:
#include "stdafx.h"
#include
using namespace std;
float RandomRge(float LB, float UB)
{
float x; x = LB + (UB - LB) / (RAND_MAX)*(float)rand(); return (x);
}
class A{
public:
A(){
English=100;
};
~A(){};
static double average(){
count++;
double ave;
Math=RandomRge(60, 100);
cout<<Math<<endl;
Math+=Math;
ave=Math/count;
return ave;
};
public:
double English;
static double Math;
static int count;
};
double A::Math=0;
int A::count=0;
class B {
public:
friend void friend_a(A &p){ //友元函数
double ave;
ave=p.average();
cout<<"count="<<p.count<<"\t"<<"Math="<<p.Math<<"\t"<<"ave="<<ave<<endl;
};
};
int _tmain(int argc, _TCHAR* argv[])
{
A a[6];
for (int i=0;i<6;i++){
friend_a(a[i]);
}
while (1);
return 0;
}
example three:
#include "stdafx.h"
#include
using namespace std;
class A;
class B {
private:
int c = 100;
public:
friend void frifun(A &p, B &pp);
};
class A {
public:
A(double r1=0,double i1=0) {
r = r1;
i = i1;
}
friend void frifun(A &p, B &pp) {
cout << p.r <<"\n"<< p.i <<"\n"<<pp.c<< endl;
}
public:
double r;
double i;
};
int main()
{
B pp;
A a1(5, 6);
frifun(a1,pp);
while (1);
return 0;
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步