这里只讲语法,因为讲原理比较难。还没有涉及到构造函数。那么就直接上代码了:
// 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关键词。