c++ 的friend用法
1.友元的内容
友元的声明自带extern 所以友元的作用域自动提升到该类的作用域所以我们可以在类内部定义友元
2.普通成员函数作为友元
该友元可以作为操作符
//OpeClass.h
#pragma once
class OpeClass
{
friend int func(const OpeClass xx);
public:
OpeClass(void);
OpeClass(int x,int y);
~OpeClass(void);
private:
int width;
int height;
};
//OpeClass.cpp
#include "OpeClass.h"
OpeClass::OpeClass(void)
{
width = 50;
height = 50;
}
OpeClass::OpeClass(int x,int y):width(x),height(y)
{
}
OpeClass::~OpeClass(void)
{
}
int func(const OpeClass xx)
{
return xx.height * xx.width;
}
//main.cpp
#include "OpeClass.h"
#include <iostream>
using namespace std;
void main()
{
OpeClass XO;
cout<<func(XO);
system("pause");
};
- 类作为友元
类作为友元在使用时要注意友元使用其他类的依赖关系,如果使用了其他类,在友元的定义文件中要带着其他类的头文件,但是在其他被引用的类文件中不用去声明
//A.h
#pragma once
#include <iostream>
using namespace std;
class A
{
friend class B;
public:
~A(void);
static void func()
{
cout<<"This is in A"<<endl;
}
private:
A(){};
static const A Test;
};
//A.cpp
#include "A.h"
const A A::Test = A();
A::~A(void)
{
}
//B.h
#pragma once
#include "C.h"
class B
{
public:
B(void);
~B(void);
void func(C& c);
};
//B.cpp
#include "B.h"
#include "A.h"
#include "C.h"
#include <iostream>
using namespace std;
B::B(void)
{
}
B::~B(void)
{
}
void B::func(C& c)
{
cout<<"This is in B"<<endl;
A::Test.func();
c.func(A::Test);
}
//C.h
#pragma once
class A;
class C
{
public:
C(void);
~C(void);
void func(const A& a);
};
//C.cpp
#include "C.h"
#include <iostream>
using namespace std;
C::C(void)
{
}
C::~C(void)
{
}
void C::func(const A& a)
{
cout<<"This is in C"<<endl;
}
//main.cpp
#include "A.h"
#include "B.h"
#include "C.h"
#include <iostream>
using namespace std;
void main()
{
B b;
C c;
b.func(c);
system("pause");
};
4.类成员函数作为友元函数
个人感觉比较复杂。。。
多文件下如果要声明友元函数的类的头文件要带友元函数的头文件,拥有友元函数的类要带声明友元函数的声明,拥有友元函数的类在。cpp文件中要带着声明友元函数的文件的头文件。
//B.h
#pragma once
class A;
class B
{
public:
B(void);
~B(void);
int func(A xx);
};
//A.h
#pragma once
#include "B.h"
class A
{
friend int B::func(A xx);
public:
A(void):mx(20),my(30){}
~A(void){}
private:
int mx;
int my;
};
//B.cpp
#include "B.h"
#include "A.h"
B::B(void)
{
}
B::~B(void)
{
}
int B::func(A xx)
{
return xx.mx * xx.my;
}
//main.cpp
#include "A.h"
#include "B.h"
#include <iostream>
using namespace std;
void main()
{
A a;
B b;
cout<<b.func(a)<<endl;
system("pause");
};
5.友元只具有单项性,不具有相互性
如果b是a的友元,那么a不一定是b的友元,要看具体声明
6.友元不能继承
如果b是a的友元,c是b的子类,推不出来c是a友元
7.友元不具备传递性
a是b的友元,b是c的友元,不能推出a是c的友元
8.互为友元的类
互为友元,多文件下不用带头文件跟类声明,但是在cpp文件需要带双方的头文件
9 如果想要指定两个类都有成员函数作为对方的友元,那么必须第2个类是第一个类的友元
最后一个没懂!!!!!
链接
https://blog.csdn.net/ddupd/article/details/38053159