C++中的Virtual Function (虚函数)
作者:网络转载 发布时间:[ 2014/3/21 9:48:10 ] 推荐标签:函数 C++
1.C++ Virtual 用法
这里只讲语法,因为讲原理比较难。还没有涉及到构造函数。那么直接上代码了:
// VitualFunction.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
//base class
class Animal{
public:
virtual void eat(){
cout << "animal eat" << endl;
}
virtual void die(){
cout << "animal die" << endl;
}
};
class Dog : public Animal{
public:
void eat(){
cout << "dog eat" << endl;
Animal::die();//use base class's function
}
};
class Cat : public Animal{
public:
void eat(){
cout << "cat eat" << endl;
}
};
class Lion : public Animal{
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<Animal*> someAnimals;
someAnimals.push_back(new Animal());
someAnimals.push_back(new Dog());
someAnimals.push_back(new Cat());
someAnimals.push_back(new Lion());
for(int i = 0; i < someAnimals.size(); ++i){
someAnimals[i]->eat();
}
system("pause");
return 0;
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11