Effective C++條款37,effective條款37

來源:互聯網
上載者:User

Effective C++條款37,effective條款37

不要重複定義virtual 函數中的參數預設值,如果重複定義,會出現程式調用過程超乎常理的結果。

大家看如下代碼:

#include<iostream>using namespace std;class Shape{public:    enum ShapeColor{Red,Green,Blue};    virtual void Drew(ShapeColor color=Red)    {        if (color == Red)            cout << "Red" << endl;        else if (color == Blue)            cout << "Blue" <<  endl;        else            cout << "Green" << endl;    }};class Rectangle :public Shape{public:    virtual void Drew(ShapeColor color=Green)    {        if (color == Red)            cout << "Red" << endl;        else if (color == Blue)            cout << "Blue" << endl;        else            cout << "Green" << endl;    }};int main(){    Shape *s = new Rectangle();    s->Drew();//調用結果列印Red,而不是Green。    return 0;}

我們肯定為結果的出乎意料而苦惱,想不通為什麼會出現這種現象。在這裡我做一個簡單地解釋。首先,大家要明白靜態繫結和動態綁定的區別。

我們的virtual函數是動態綁定的調用過程,它的調用決策者是實際指向的對象。而我們函數中預設值的選定卻是靜態繫結,它的決策者是當前正在調用的物件類型。

我們看上面的例子,s指標是shape類的,實際指向Rectangle類的對象,調用Drew函數時由於Drew是virtual函數,所以調用Rectangle類中的Drew函數,可是選擇的函數參數預設值卻是Shape類的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.