爲什麼虛函數(virtual)不能是static函數


title: 爲什麼虛函數(virtual)不能是static函數
date: 2016-06-08 15:22:30
categories: C++
tags:
- C++
- C


簡而言之,成員函數實例相關,靜態函數類相關。

虛函數,是一種特殊的成員函數,用來實現運行時多態。

  • 靜態成員函數,可以不通過對象來調用,沒有隱藏的this指針。
  • virtual函數一定要通過對象來調用,有隱藏的this指針。

所以,關鍵問題是static成員沒有this指針。

static function 是靜態決議(編譯的時候就綁定了)

而virtual function 是動態決議的(運行時才綁定)

引用stackoverflow網友@Kerrek SB 的回答:

That would make no sense. The point of virtual member functions is that they are dispatched based on the dynamic type of the object instance on which they are called. On the other hand, static functions are not related to any instances and are rather a property of the class. Thus it makes no sense for them to be virtual. If you must, you can use a non-static dispatcher.

即是說:virtual成員函數的關鍵是動態類型綁定的實例調用。然而,靜態函數和任何類的實例都不相關,它是class的屬性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章