1.虚析构 纯虚析构
#include<iostream>
#include<string>
using namespace std;
//虚析构 纯虚析构
//
class Animal
{
public:
Animal()
{
cout << "已构造Animal 对象" << endl;
}
virtual void speak() = 0;//虚函数
//虚析构
/*virtual~Animal()
{
cout << "Animal 已销毁" << endl;
}*/
//纯虚析构
//先在类内声明
virtual ~Animal() = 0;
};
//再在类外具体实现 要加上作用域
Animal::~Animal()
{
cout << "Animal 已销毁" << endl;
}
class Cat :public Animal
{
public:
Cat(string name)
{
this->name = new string(name);//子类对象中有堆区内容,需要程序员自己在析构中释放
//但在销毁父类指向子类对象的指针时,并无法调用子类的析构函数
//需要在父类的虚构函数前加上virtual 使其成为虚析构函数,才能调用子类的析构函数
cout << "Cat 已构造" << endl;
}
void speak()
{
cout << *name<<" is speaking" << endl;
}
string* name;
~Cat()
{ cout << "Cat 已析构" << endl;
if (name != NULL)
{
delete name;
name = NULL;
}
}
};
void test05()
{
string name;
cin >> name;
Animal* ptr=new Cat (name);
ptr->speak();
delete ptr;
}
int main05()
{
test05();
return 05;
}
2.案例--组装电脑
#include<iostream>
using namespace std;
//电脑组装
//三个部件 CPU Video_card Memory
//分别 把这三个部件对应执行的函数构造成纯虚函数,方便不同品牌部件扩展自己的功能
//三个类也因纯虚函数成为抽象类
class CPU
{
public:
// 计算
virtual void calculator() = 0;
};
class Video_card
{
public:
//显示
virtual void display() = 0;
};
class Memory
{
public:
//存储
virtual void store() = 0;
};
//组装计算器
class Computer
{
public:
Computer(CPU* cc, Video_card* xx, Memory* mm)
{
cpu = cc;
xianka = xx;
Memory = mm;
cout << "computer 已构造" << endl;
}
Computer(Computer& cpr)
{
cpu = cpr.cpu;
xianka = cpr.xianka;
Memory = cpr.Memory;
}
/*Computer(CPU &cc, Video_card& xx, Memory & mm)
{
cpu = &cc;
xianka = &xx;
Memory = &mm;
}*/
~Computer()
{
if (cpu != NULL)
{
delete cpu;
cpu = NULL;
cout << "cpu 已释放!" << endl;
}
if (xianka != NULL)
{
delete xianka;
xianka = NULL;
cout << "xianka 已释放!" << endl;
}
if (Memory != NULL)
{
delete Memory;
Memory = NULL;
cout << "Memory 已释放!" << endl;
}
cout << "computer 已释放" << endl;
}
void run()
{
cpu->calculator();
xianka->display();
Memory->store();
}
private:
CPU* cpu;
Video_card* xianka;
Memory* Memory;
};
//具体化 三个部件
class INCPU :public CPU
{
public:
void calculator()
{
cout << "In is 计算ing" << endl;
}
};
class INMemory :public Memory
{
public:
void store()
{
cout << "In is storing" << endl;
}
};
class INVideo_card : public Video_card
{
public:
void display()
{
cout << "In is 显示ing" << endl;
}
};
//
class ENCPU :public CPU
{
public:
void calculator()
{
cout << "EN is 计算ing" << endl;
}
};
class ENMemory :public Memory
{
public:
void store()
{
cout << "EN is storing" << endl;
}
};
class ENVideo_card : public Video_card
{
public:
void display()
{
cout << "EN is 显示ing" << endl;
}
};
void test06()
{
CPU * ic = new INCPU;
Video_card* ix = new INVideo_card;
Memory* im = new INMemory;
Computer* IN = new Computer(ic, ix, im);//组装IN类
IN->run();
delete IN;//需要自己写析构把堆区成员释放
IN = new Computer(new ENCPU,new ENVideo_card,new ENMemory);//组装EN类
IN->run();
Computer* EN = new Computer(*IN);//拷贝构造IN类
EN->run();
delete IN;
//拼装 I_E 类
IN = new Computer(new INCPU, new ENVideo_card, new INMemory);
IN->run();
delete IN;
IN = NULL;
}
int main()
{
test06();
}