關於純虛函數

#include "stdafx.h"
#include<iostream>   
using namespace std;ios

//1.一個類中能夠聲明一個或多個純虛函數,只要有純虛函數的類就是抽象類
//2.抽象類只能做爲其餘類的基類,不能用來創建對象,又稱抽象基類
//3.若是派生類只是簡單地繼承了抽象類的純虛函數,而沒有從新定義基類的純虛函數,則派生類也是一個抽象類函數

class A{ 
public:
 virtual void fun() = 0;          //純虛函數
};spa

class B:public A{
public:
 void fun(){cout<<"實現純虛函數的定義成功"<<endl;}  //重寫基類純虛函數
};對象

//只有派生類與基類的虛函數具備徹底相同的函數名、返回類型以及參數表,才能實現虛函數的特性
class C:public A{
public:
 void fun(int i){cout << "fun(int i)並非基類純虛函數fun()的實現版本"<<endl;}
};
 繼承

//PS:如下兩種聲名沒有區別
int *i,j = NULL;
int* p,q = NULL;
 ci

int _tmain(int argc, _TCHAR* argv[])
{
cout << i << endl;
cout << j << endl;
cout << p << endl;
cout << q << endl;
 get

 //A a;              //錯誤:A是抽象類,不能創建對象
   B b;
 //C c;              //錯誤:C並無實現基類的純虛函數,因此C還是抽象類,不能創建對象
 io

 A *p1 = NULL;
 A *p2 = NULL;class

 p1 = &b;
 p2 = new B;
 stream

//p1.fun();           //錯誤:left of '.fun' must have class/struct/union
//p2.fun();           //錯誤:left of '.fun' must have class/struct/union
 p1->fun();
 p2->fun();
 

  A &a = b;
 a.fun();
//a->fun();           //錯誤:type 'A' does not have an overloaded member 'operator ->'
                           //錯誤: '->A::fun' : left operand has 'class' type, use '.’

 cin.get();  return 0; }

相關文章
相關標籤/搜索