C++中的Virtual Function (虚函数)

Bonita ·
更新时间:2024-11-13
· 809 次阅读

  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; }



c+ 函数 虚函数 C++ virtual

需要 登录 后方可回复, 如果你还没有账号请 注册新账号