4.7.6电脑组装
#include <iostream>
using namespace std;
class CPU
{
public:
virtual void caculate() = 0;
};
class videocard
{
public:
virtual void display() = 0;
};
class memory
{
public:
virtual void storage() = 0;
};
class computer
{
public:
computer(CPU *cpu, videocard * vc, memory *mem)
{
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}
void work()
{
m_cpu->caculate();
m_vc->display();
m_mem->storage();
}
private:
CPU *m_cpu;
videocard * m_vc;
memory *m_mem;
};
class intelcpu :public CPU
{public:
virtual void caculate()
{
cout << "intel__cpu" << endl;
}
};
class intelvideocard :public videocard
{
public:
virtual void caculate()
{
cout << "intel__videocard" << endl;
}
};
class intelmemory :public memory
{
public:
virtual void caculate()
{
cout << "intel__memory" << endl;
}
};
class lenovocpu :public CPU
{
public:
virtual void caculate()
{
cout << "lenovo__cpu" << endl;
}
};
class lenovovideocard :public videocard
{
public:
virtual void caculate()
{
cout << "lenovo__videocard" << endl;
}
};
class lenovomemory :public memory
{
public:
virtual void caculate()
{
cout << "lenovo__memory" << endl;
}
};
void test01()
{
CPU *intelcpu = new lenovocpu;
videocard *intelcard = new lenovovideocard;
memory *intelmemo = new intelmemory;
computer *c1 = new computer(intelcpu, intelcard, intelmemo);
c1->work();
}
int main()
{
test01();
system("pause");
return 0;
}
4.7.5虚析构和纯虚虚构
#include <iostream>
using namespace std;
#include<string>
class Animal
{
public:
Animal()
{
cout << "Animal" << endl;
}
virtual void speak() = 0;
virtual ~Animal()
{
cout << "~Animal" << endl;
}
};
class cat :public Animal
{
public:
cat(string name)
{
cout << "cat()" << endl;
m_name = new string(name);
}
virtual void speak()
{
cout << *m_name<<" cat speak" << endl;
}
string *m_name;
~cat()
{
if (m_name != NULL)
{
cout << "~cat()" << endl;
delete m_name;
m_name = NULL;
}
}
};
void test01()
{
Animal *ani = new cat("tom");
ani->speak();
delete ani;
}
int main4_7_5()
{
test01();
system("pause");
return 0;
}