#include <iostream>
using namespace std;
// 前向声明
class TV;
// 友元类声明(其中的几个函数为友元)
class Remote
{
public:
void volume_to(TV &tv, int x);
void channel_to(TV &tv, int x);
};
// 类声明
class TV
{
public:
enum{off=0, on=1};
// 声明友元函数
friend void Remote::volume_to(TV &tv, int x);
friend void Remote::channel_to(TV &tv, int x);
// 成员函数
TV(int st=on):state(st),channel(5),volume(20){};
void onoff(){state^=1; cout<<"now state is "<<(state?"on":"off")<<endl;}
void chan_next(){cout<<"now channel is "<<++channel<<endl;}
void chan_last(){cout<<"now channel is "<<--channel<<endl;}
void vol_larger(){cout<<"now volume is "<<++volume<<endl;}
void vol_smaller(){cout<<"now volume is "<<--volume<<endl;}
private:
int channel;
int volume;
int state;
};
c++ 友元类 练习题
最新推荐文章于 2024-07-17 22:45:00 发布
本文通过一个练习题探讨了C++中友元类的使用,强调了在声明和调用友元函数时需要预先定义相关函数,并指出TV类和Remote类的声明顺序至关重要。TV类必须在Remote类前定义,而Remote类需要TV类的前向声明,且Remote类只能含有友元函数的声明,具体实现应在TV类之后完成。
摘要由CSDN通过智能技术生成