设为首页 加入收藏

TOP

C++中的Virtual Function (一)
2014-04-06 17:35:38 来源: 作者: 【 】 浏览:154
Tags:Virtual  Function 

  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();

  }

  }

  }

   

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇char *p 与char p.. 下一篇C/C++位操作初步

评论

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

·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)
·Redis配置中`require (2025-12-26 03:18:58)
·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)