歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++ 中的Virtual Function (虛函數)

C++ 中的Virtual Function (虛函數)

日期:2017/3/1 9:47:09   编辑:Linux編程

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;
&nbsp;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
&nbsp;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關鍵詞。

Copyright © Linux教程網 All Rights Reserved