多态学习记录:使用以下示例让我对多态的知识大彻大悟:)
目的:用C++创建类,使用多态建立显卡、cpu、内存,并最后打印输出。
分别建立一个抽象的类:(创建抽象类,是多态的精髓)
class CPU
{
vitural void calcutor() = 0;
};
class Memory
{
vitural void storage() = 0;
};
class VideoCard
{
vitural void display() = 0;
};
创建一台电脑(父类)
class Computer
{
public:
Computer(CPU* cpu,Memory* memory, VideoCard* videocard)//创建构造函数取得private
{
m_cpu = cpu;
m_memory = memory;
m_videocard = videocard;
}
//创建work函数实现打印
void work()//调用各零件的所含函数
{
m_mpu->caltator();
m_memory->display();
m_videocard->storage();
}
private:
CPU* m_cpu;
Memory* m_memory;
VideoCard* m_videocard;
};
创建显卡等具体类型(用英特尔brand,英特尔记得打钱)
***创建具体类型相当于把之前抽象的类具体化***
//创建具体类型相当于把之前抽象的类具体化
class IntelCPU:public CPU//继承抽象类
{
vitural void calcutor()
{
cout<<"显卡正在运行"<<endl;
}
};
class Interalmemory :public Memory
{
virtual void display()
{
cout << "内存正在运行" << endl;
}
};
class Interalcpu :public CPU
{
virtual void calcutor()
{
cout << "CPU正在运行" << endl;
}
};
写一个测试案例:实现对上述三者的打印(创造一个父类指针指向子类对象实现目的)
void test()
{
//引入电脑零件(使用指针的方式)
CPU *cpu = new IntelCPU;//CPU是父类的,使用指针的方式,指向子类IntelCPU
Memory* intelmemory = new Interalmemory;
VideoCard* vc = new InteralVideo;
方法一:
//创建一台电脑(指针方式实现)
Computer *computer1 = new Computer(IntelCPU,Interalmemory,InteralVideo)//调用父类构造函数
//引出类内函数
computer1->work();
方法二:不用指针的方式
Computer computer1 =Computer(IntelCPU,Interalmemory,InteralVideo)//调用父类构造函数
computer2.work();
}
结果:
至此,C++三大特征基本语法学习完毕。接下来开启STL的学习之路!UP!
2023年2月18日20:02:07