虛函數中的預設實參

來源:互聯網
上載者:User

C++premier

先看例子吧

#include"iostream"
using namespace std;
class base{
public:virtual int foo(int ival=1024){
   
     cout<<"base::foo()--ival:"<<ival<<endl;
     return ival;
    }

};
class derived:public base{
public:int foo(int ival=2048){
     cout<<"derived::foo()--ival:"<<endl;
      return ival;
    }
};
int main()
{
derived *pd=new derived;
base *pb=pd;
int val =pb->foo();
cout<<"main():val through base:"<<val<<endl;
val=pd->foo();
cout<<"main():val through derived:"
<<val<<endl;
}

我是初學C++,用編譯器運行突然發現輸出的是

好像有點不對啊,從結果derived::foo()--ival都是調用了derived裡的foo,符合多態的機制,但是問題是1024和2048怎麼回事呢?

書上是這麼解釋的,供大家參考:

調用的真正函數是在運行時刻pb和pd指向的類型所決定,也就是晚捆綁,而預設實參是在編譯時間刻就根據被調用函數的對象的類型所決定。具體解釋可見C++ PREMIER   page771.第三版哦。

聯繫我們

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