c++多态性和纯虚函数
来源:互联网 发布:mac上如何制作铃声 编辑:程序博客网 时间:2024/05/22 17:37
多态性:
多态性作用于基类和子类之间,如果基类的函数加了virtual称为虚函数,则对象调用的函数则是他自己的函数(就是子类则调用它自己的函数,不会调用基类同名的虚函数)。反之如果基类和子类之间同时存在同名函数,则调用基类函数。
#include <iostream>using namespace std;class animal{public:virtual void color(){cout << "same color !" << endl;}};class dog : public animal{public:void color(){cout << "the dog color is white" << endl;}};void testContrustor(animal *animal){animal -> color();}int main(){dog dog;animal *animal;animal = &dog;testContrustor(animal); return 0;}
结果将是: “the dog color is white”。
虚函数:
纯虚函数是作用于基类和子类关系中,基类声明 了函数,却没有实现函数,需要在继承基类,在子类中实现该函数。声明的该函数是virtual前缀的虚函数。
// Note:Your choice is C++ IDE#include <iostream>using namespace std;class animal{public:virtual void color()=0;};class dog : public animal{public:void color(){cout << "the dog color is white" << endl;}};class cat : public animal{public:void color(){cout << "the dog color is black" << endl;}};int main(){ dog dog; dog.color(); cat cat; cat.color(); return 0;}运行结果为:“the dog color is white”和“the dog color is black”
0 0
- 多态性和虚函数、纯虚函数
- C++中的多态性和纯虚函数
- 多态性:纯虚函数和抽象类
- C++中的多态性和纯虚函数
- c++多态性和纯虚函数
- C++-虚函数,多态性,纯虚函数,抽象类
- c++--多态性和虚函数
- C++多态性基本概念 包括虚函数和纯虚函数
- C++多态性基本概念 包括虚函数和纯虚函数
- 虚函数与多态性、纯虚函数
- 虚函数与多态性 纯虚函数
- 虚函数与多态性/纯虚函数
- 虚函数与多态性,纯虚函数
- 虚函数和多态性2——抽象基类和纯虚函数
- 【原创】多态性、动态多态性、静态多态性、虚函数、纯虚函数、抽象类总结
- 多态性和虚函数
- 虚函数和多态性
- 虚函数和多态性
- Django代码部署到CentOS服务器上
- Edit Distance(编辑距离)算法。计算两个字符串的相似程度。
- POJ 2182 Lost Cows 线段树
- P51.14
- QtWebkit实现视频透明区域
- c++多态性和纯虚函数
- WCF大数据量传输配置
- Linux分屏
- hdu 5201 容斥原理+组合数取模
- 几步搞定Maven+Eclipse做ArcObjects二次开发
- Accessing an OpenCV Mat Data using C++
- c/c++遍历文件夹
- 五大常用算法之三:贪心算法
- 啤酒和饮料