C++基本概念学习
来源:互联网 发布:网络编辑招聘 编辑:程序博客网 时间:2024/06/10 10:35
虚函数
虚函数 基类中的一类成员函数;允许子类根据自己的需要重新定义。
纯虚函数 在父类中不提供具体实现的虚函数。
//文件:Shapes.h
#ifndef _SHAPE_H
#define _SHAPE_H
#include <iostream>
using namespace std;
class Shape
{
public:
//纯虚函数,没有实际的函数定义
virtual void WhatAmI()=0;
};
class Pyramid:public Shape
{
public:
void WhatAmI() {cout<<"/n I am a pyramid./n";}
};
class Sphere:public Shape
{
public:
void WhatAmI() {cout<<"/nI am a sphere./n";}
};
class Cone:public Shape
{
public:
void WhatAmI() {cout<<"/nI am a cone./n";}
};
class Box:public Shape
{
public:
void WhatAmI() {cout<<"/n I am a box./n";}
};
#endif
#ifndef _SHAPE_H
#define _SHAPE_H
#include <iostream>
using namespace std;
class Shape
{
public:
//纯虚函数,没有实际的函数定义
virtual void WhatAmI()=0;
};
class Pyramid:public Shape
{
public:
void WhatAmI() {cout<<"/n I am a pyramid./n";}
};
class Sphere:public Shape
{
public:
void WhatAmI() {cout<<"/nI am a sphere./n";}
};
class Cone:public Shape
{
public:
void WhatAmI() {cout<<"/nI am a cone./n";}
};
class Box:public Shape
{
public:
void WhatAmI() {cout<<"/n I am a box./n";}
};
#endif
再声明一个指向基类的指针,并把一个派生类的地址赋给该指针(这在C++中是合法的),就可以通过这个指针来访问派生类中的虚函数。
//文件:VirtualShapesDriver.cpp
#include <iostream>
using namespace std;
#include "Shapes.h"
int main()
{
cout<<"/n The Virtual Shapes Program"<<endl;
Shape *basePtrs[4]; //创建一个基类指针数组
Sphere MySphere;
Pyramid MyPyramid;
Cone MyCone;
Box MyBox;
basePtrs[0]=&MyCone; //将子类的地址保存到基类指针数组中
basePtrs[1]=&MySphere;
basePtrs[2]=&MyPyramid;
basePtrs[3]=&MyBox;
//通过遍历数组可以访问每个对象的WhatAmI函数
for(int i=0;i<4;++i)
{
basePtrs[i]->WhatAmI();
}
cout<<"/n Very cool,don't you think?"<<endl;
return 0;
}
#include <iostream>
using namespace std;
#include "Shapes.h"
int main()
{
cout<<"/n The Virtual Shapes Program"<<endl;
Shape *basePtrs[4]; //创建一个基类指针数组
Sphere MySphere;
Pyramid MyPyramid;
Cone MyCone;
Box MyBox;
basePtrs[0]=&MyCone; //将子类的地址保存到基类指针数组中
basePtrs[1]=&MySphere;
basePtrs[2]=&MyPyramid;
basePtrs[3]=&MyBox;
//通过遍历数组可以访问每个对象的WhatAmI函数
for(int i=0;i<4;++i)
{
basePtrs[i]->WhatAmI();
}
cout<<"/n Very cool,don't you think?"<<endl;
return 0;
}
嘿嘿,今天终于知道什么是虚函数了。
- 学习C的一些基本概念(一)
- 初步学习C++:C++的基本概念
- C#基本概念
- c基本概念
- C基本概念
- 《Linux C一站式学习》第一章 程序的基本概念
- 《C和指针》学习笔记二/基本概念和数据/
- C语言学习笔记(1)--基本概念和函数用法
- iOS学习(十八)Objective-C 多态的基本概念
- 编程学习小结(1)基本概念----c语言
- C中一些基本概念
- C语言的基本概念
- xml基本概念C
- [C#]基本概念:堆栈
- C语言-向量基本概念
- C基本概念(一)
- C语言基本概念
- C语言基本概念理解
- 汇编与C/C++的混合使用
- 碰到的一些笔试题C语言方面
- Ubuntu 安装 php
- poj3321——Apple Tree//树状数组
- 一些要掌握的基础知识
- C++基本概念学习
- 单片机学习笔记
- MATLAB--自定义函数
- C++类对象内存模型与成员函数调用分析(下)
- I' m Really
- 气场——改变全球1600万人命运的强大蝴蝶效应
- abstract , interface, 和final
- poj2352——Stars//树状数组
- 重写GridView,支持CheckBox选择,List排序等等...