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#和Java的。当子类重写父类方法时,连个关键词都没有,就重写了。还有调用父类的方法,连个关键词都没有,直接名字加::就调用了,也太不尊重父类了。这可能是C++支持多重继承的语法决定。
2.C#中的virtual用法
using System; using System.Collections.Generic; using System.Text; namespace VirutalFunctionCShape { //base class public class Animal{ public virtual void eat(){ Console.WriteLine("Animal eat"); } public virtual void die(){ Console.WriteLine("Animal die"); } } public class Dog : Animal{ public override void eat() { Console.WriteLine("Dog eat"); base.die(); } } public class Cat : Animal{ public override void eat() { Console.WriteLine("Cat eat"); } } public class Lion : Animal{ } class Program { static void Main(string[] args) { IList<Animal> someAnimals = new List<Animal>(); someAnimals.Add(new Animal()); someAnimals.Add(new Dog()); someAnimals.Add(new Cat()); someAnimals.Add(new Lion()); foreach (Animal animal in someAnimals) { animal.eat(); } Console.ReadLine(); } } }
C#中比C++好多了,重写的时候加上了override关键词,调用父类的方法时候加上了base关键词。
3.java 中的 Virtual
import java.util.LinkedList; import java.util.List; public class Animal { public void eat(){ System.out.println("Animal eat"); } public void die() { System.out.println("Animal die"); } /** * @param args */ public static void main(String[] args) { List<Animal> someAnimals = new LinkedList<Animal>(); someAnimals.add(new Animal()); someAnimals.add(new Dog()); someAnimals.add(new Cat()); someAnimals.add(new Lion()); for(Animal animal : someAnimals){ animal.eat(); } } } public class Cat extends Animal{ @Override public void eat() { System.out.println("Cat eat"); } } public class Dog extends Animal{ @Override public void eat(){ System.out.println("Dog eat"); super.die(); } } public class Lion extends Animal{ }
java这里好方便,尼玛所有函数默认就是virtual函数,连个virtual关键词都没有,好了,你们要随便重写你们自己搞。重写的时候加上个@override关键词。好像有时候不用也行,看jdk版本。调用父类方法的关键词是super。还行。
参考: