c++拾遺(二)

來源:互聯網
上載者:User
  1. 虛函數

使得在基類聲明的函數能夠在各個衍生類別裡面重新定義。比如下面這個例子

   1: #include <iostream>

   2: #include <string>

   3: using namespace std;

   4: class Employee{

   5:     string first_name, family_name;

   6:     short department;

   7: public:

   8:     Employee(const string &n, int d);

   9:     virtual void print() const;

  10: };

  11: void Employee::print()const{

  12:     cout<<family_name<<department<<endl;

  13: }

  14: Employee::Employee(const string &n, int d):first_name(n),department(d){}

  15: class Manager:public Employee{

  16:     //list<Employee*> group;

  17:     short level;

  18: public:

  19:     Manager(const string &n, int d, int lvl);

  20:     void print()const;

  21: };

  22: Manager::Manager(const string &n, int d , int lvl):Employee(n,d),level(lvl){}

  23: void Manager::print() const

  24: {

  25:     Employee::print();

  26:     cout<<level<<endl;

  27: }

  28: int main()

  29: {

  30:     Employee e("Brown",1234);

  31:     Manager m("Smith",1234,2);

  32:     e.print();

  33:     m.print();

  34:     Employee *p = &e;

  35:     p->print();

  36:     p = &m;

  37:     m.print();

  38:     Manager *q = &m;

  39:     q->print();

  40:  

  41: }

 

基類聲明了一個虛函數 virtual void print() const; 用來列印類成員的資訊。在基類和衍生類別中分別定義print函數的具體內容。

在實現中定義一個指向基類對象的指標,分別用基類和衍生類別的對象地址賦值。然後通過指標調用print函數,可以發現,調用的分別是基類和衍生類別定義的print函數。

對於給定的類型為base*的指標,被指的對象到底屬於哪個衍生類別呢?通過虛函數,我們解決了這個問題。程式的輸出為:

   1: 1234

   2: 1234

   3: 2

   4: 1234

   5: 1234

   6: 2

   7: 1234

   8: 2

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.