C++_友元类
来源:互联网 发布:nginx从入门到精通 pdf 编辑:程序博客网 时间:2024/05/13 02:43
#include <iostream>using namespace std;class TV // 电视机类{public: friend class Tele; // friend是关键字,代表类Tele是类TV的友元类 TV():on_off(off),volume(20),channel(3),mode(tv){}private: enum{on = 0, off = 1}; enum{tv = 0, av = 1}; enum{minvol = 0, maxvol = 100}; enum{minchn = 0, maxchn = 60}; bool on_off; // 开关 int volume; // 音量 int channel; // 频道 int mode; // 模式 /* 如果某个类有一个友元类,那么该类的私有成员及其保护成员都会暴露给友元类,友元类可通过自己的方法来访问该类的所有成员。 */};class Tele // 遥控器类{public: void OnOff(TV &t) { t.on_off = (t.on_off == t.on) ? t.off : t.on; // 正是因为类Tele是类TV的友元类,所以类Tele可以直接操作类TV的所有私有成员 } void SetMode(TV &t) { t.mode = (t.mode == t.tv) ? t.av : t.tv; } bool VolumeUp(TV &t); bool VolumeDown(TV &t); bool ChannelUp(TV &t); bool ChannelDown(TV &t); void show(TV &t)const;};bool Tele::VolumeUp(TV &t){ bool bVol; if (t.volume < t.maxvol) { t.volume ++; bVol = true; } else { bVol = false; } return bVol;}bool Tele::VolumeDown(TV &t){ bool bVol; if (t.volume > t.minvol) { t.volume --; bVol = true; } else { bVol = false; } return bVol;}bool Tele::ChannelUp(TV &t){ bool bChn; if (t.channel < t.maxchn) { t.channel ++; bChn = true; } else { bChn = false; } return bChn;}bool Tele::ChannelDown(TV &t){ bool bChn; if (t.channel > t.minchn) { t.channel --; bChn = true; } else { bChn = false; } return bChn;}void Tele::show(TV &t)const{ if (t.on_off == t.on) { cout << "电视机现在的状态:" << "开始" << endl; cout << "音量大小为:" << t.volume << endl; cout << "频道为:" << t.channel << endl; cout << "信号接受模式为:" << t.mode << endl; } else { cout << "电视机现在的状态:" << "关闭" << endl; }}int main(){ Tele t1; TV t2; t1.show(t2); t1.OnOff(t2); t1.show(t2); cout << "调大声音" << endl; t1.VolumeUp(t2); cout << "频道+1" << endl; t1.ChannelUp(t2); cout << "转换模式" << endl; t1.SetMode(t2); t1.show(t2); return 0;}
0 0
- C++_友元类
- c+_+
- C/C++_
- C/C++_扫雷
- C#_多线程_ 整理
- C#_事件_委托
- [C/C++]_[初级]_[原子操作]
- C#_值类型
- C#_委托
- C#_值类型
- C#_泛型
- c#_接口
- C#_递归算法
- C++_文件读写
- C++_引用
- C++_静态成员
- C++_类型转换
- C#_抖动
- this到底是谁
- SDUTOJ 2121 数据结构实验之链表六:有序链表的建立
- java中简单字符替换
- 健康——每日最佳饮水时间
- UVa 753 - A Plug for UNIX(最大流 | EK)
- C++_友元类
- leetcode - Validate Binary Search Tree
- 香港战争
- 将字符串切割成数组 componentsSeparatedByString
- rapidxml读取结点内容操作
- 黑马程序员——对OC面向对象的完整总结
- 2080夹角有多大II
- UVA - 10790 How Many Points of Intersection?
- ABAP program lines are wider than the internal table