一、tv遥控器的模拟
#include<iostream>
using namespace std;
class TV {
friend class Remote;
public:
enum {on, off};
enum{minvolume, maxvolume = 50};
enum{minchannel, maxchannel = 150};
TV()
{
mstate = 0;
volume = 0;
channel = 0;
}
void turntv() {
this->mstate == this->mstate == on ? off:on;
}
void upchannel() {
if (this->channel >= maxchannel )
{
return;
}
this->channel++;
}
void downchannel() {
if (this->channel <= minchannel) {
return;
}
this->channel--;
}
void upvolume() {
if (this->volume >= maxvolume)
{
return;
}
this->volume++;
}
void downvolume() {
if (this->volume <= minvolume)
{
return;
}
this->volume--;
}
void showinfo()
{
cout << "当前电视为" << (mstate == on ? "开启状态" : "关闭状态") << endl;
cout << "当前频道为" << channel << endl;
cout << "当前音量为" << volume << endl;
}
private:
int mstate;
int volume;
int channel;
};
class Remote {
public:
Remote(TV *teletvtion) {
mtv = teletvtion;
}
public:
void turn() { mtv->turntv(); }
void upchannel(){mtv->upchannel();}
void downchannel(){mtv->downchannel();}
void upvolume() { mtv->upvolume(); }
void downvolume() { mtv->downvolume(); }
void showinfo() { mtv->showinfo(); }
void setchannel(int channel){
if (channel >= mtv->maxchannel || channel <= mtv->minchannel)
{
cout << "无当前频道" << endl;
return;
}
mtv->channel = channel;
}
private:
TV* mtv;
};
void test03()
{
TV tv1;
tv1.turntv();
tv1.upchannel();
tv1.upvolume();
tv1.upvolume();
tv1.showinfo();
}
void test02()
{
TV tv2;
Remote tv2cont(&tv2);
tv2cont.turn();
tv2cont.upchannel();
tv2cont.upchannel();
tv2cont.showinfo();
tv2cont.setchannel(15);
tv2cont.showinfo();
}
void main()
{
test02();
}
二、智能指针(指针运算符(*、->)重载)
#include<iostream>
using namespace std;
class Person {
public:
Person(int age)
{
m_age = age;
}
void showinfo()
{
cout << "此人的年龄为" << m_age << endl;
}
private :
int m_age;
};
class smartpointer {
public:
smartpointer(Person* people)
{
m_person = people;
cout << "进行smartpointer的构造函数" << endl;
}
~smartpointer()
{
if (m_person != NULL)
{
delete m_person;
m_person == NULL;
}
cout << "调用smartpointer的析构函数" << endl;
}
Person* operator->()//返回地址
{
return m_person;
}
Person& operator*()//返回地址中的内容(类)
{
return *m_person;
}
private:
Person* m_person;
};
void test04()
{
smartpointer ti = smartpointer(new Person(200));
ti->showinfo();
(*ti).showinfo();
}
void main() {
test04();
}
结果:
通过智能指针的实现,在函数中使用new从栈区开辟空间后,不用手动delete,在类中析构函数会自动进行delete操作。smartpointer ti = smartpointer(new Person(200));中,首先通过new在栈区中开辟地址,紧接着通过smartpointer中的构造函数使其类中的指针成员m_person指向new开辟的地址,紧接着通过对->与*的重载操作new开辟的person类的地址。
智能指针的实现虽然使得在函数中不需要手动调用delete释放空间,但是在函数中的临时空间在函数结束后被立刻释放,无法保存。
此类方法实际中很少使用。