friend声明可以位于类的任何地方
class B
{
...
friend class A;//在类中声明A为该类的友元类
...
}
友元类A可以访问B类的公有,私有,保护成员,友元不能强加,只能有类自己指定
也可以只声明友元函数,指定Remote类的某个成员函数为TV类的友元
不过使用时有严格的声明顺序要求
class TV; //声明tv类,因为在Remote类中声明了TV类指针
class Remote { ....;SetVol()};
class TV {....;friend Remote::SetVol()};
inline void Remote::SetVol() { ..... } //函数中使用楼TV类成员函数,需要在TV类定义了后再定义,可以在之前声明
#include <iostream>
using namespace std;
class TV; //声明tv类
class Remote
{
private:
TV *m_ptv;
public:
Remote(TV *ptv):m_ptv(ptv) {}
void onOff();
//void volUp() { m_ptv->volUp();}
//void volDown() { m_ptv->volDown();}
void SetVol();
};
class TV
{
private:
enum {On, Off};
enum {Tv, Av};
int state;
int volume;
int channel;
public:
TV(int vol, int chan, int st = Off):state(st),volume(vol),channel(chan) {}
bool isOn() const { return state == On; };
void onOff() {state = (state = On) ? Off : On;}
void volUp() { volume++;}
void volDown() { volume--;}
void chanUp() { channel++;}
void chanDown() { channel--;}
void GetPar() {cout << "state:" << state << endl
<< "volume:" << volume << endl
<< "channel:" << channel << endl;}
//friend class Remote;
friend void Remote::SetVol();
};
void Remote::SetVol()
{
m_ptv->volume = 20;
}
void Remote::onOff()
{
m_ptv->onOff();
}
int main()
{
TV *pTv = new TV(0, 1);
Remote objR(pTv);
pTv->GetPar();
objR.onOff();
//objR.volUp();
pTv->GetPar();
objR.SetVol();
pTv->GetPar();
delete pTv;
}
2个类可以互相声明为友元类,需要注意的是声明和定义的顺序:假如TV类成员函数要使用Remote类的成员,可以在remote类声明之前声明,但是一定要在remote类声明之后定义,以便编译器有足够的信息编译