设为首页 加入收藏

TOP

C++ 中的Virtual Function (虚函数)
2014-11-24 01:01:08 来源: 作者: 【 】 浏览:2
Tags:Virtual Function 函数

1.C++ Virtual 用法


这里只讲语法,因为讲原理比较难。还没有涉及到构造函数。那么就直接上代码了:


// VitualFunction.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include
#include


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 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 someAnimals = new List();
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关键词。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux-2.6驱动开发 下一篇C++ Copy Constructor (拷贝构造..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: