c++ 友元类 练习题

本文通过一个练习题探讨了C++中友元类的使用,强调了在声明和调用友元函数时需要预先定义相关函数,并指出TV类和Remote类的声明顺序至关重要。TV类必须在Remote类前定义,而Remote类需要TV类的前向声明,且Remote类只能含有友元函数的声明,具体实现应在TV类之后完成。
摘要由CSDN通过智能技术生成
#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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值