纯虚函数

上一篇 / 下一篇  2007-11-27 16:33:28 / 个人分类:c++

纯虚函数: virtual 返回类型 函数名(参数列表) = 0;

含有 纯虚函数 的类称为: 抽象类(abstract class)

抽象类:不能作为 数据类型,不能自己建立对象; 函数返回值; 显示转化类型;

      只能做基类.

实例:

// 纯虚函数.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
///
class Animal
{
public:
 virtual void sound() = 0;//纯虚函数..interface..
};
////
class Dog:public Animal
{
public:
 void sound() = 0;//保持纯虚函数特性..
};
////
class Cat:public Animal
{
public:
 void sound()
 {
  cout <<"miaow-...-miaow"<<endl;
 }
};
////
void animal_sound(Animal *pAnimal)
{
 pAnimal->sound();
}
////main()
int _tmain(int argc, _TCHAR* argv[])
{
// Animal a;
// Animal *pAnimal = new Animal();
// Animal *pDog = new Dog();
 Animal *pCat = new Cat();

// pAnimal->sound();
// pDog->sound();
 pCat->sound();
 cout<<endl;


// animal_sound(pAnimal);
// animal_sound(pDog);
 animal_sound(pCat);

// delete pAnimal;
// delete pDog;
 delete pCat;

 getchar();
 return 0;
}


TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

Open Toolbar