c++的overload override overwrite 你真的懂了嗎

以下是對C++中overload,override,overwrite的區別進行了詳細的分析介紹,需要的朋友可以過來參考下

Overload(重載):在C++程序中,可以將語義、功能相似的幾個函數用同一個名字表示,但參數或返回值不同(包括類型、順序不同),即函數重載。
(1)相同的範圍(在同一個類中);
(2)函數名字相同;
(3)參數不同;
(4)virtual 關鍵字可有可無。

Override(覆蓋):是指派生類函數覆蓋基類函數,特徵是:
(1)不同的範圍(分別位於派生類與基類);
(2)函數名字相同;
(3)參數相同;
(4)基類函數必須有virtual 關鍵字。

Overwrite(重寫):是指派生類的函數屏蔽了與其同名的基類函數,規則如下:
(1)如果派生類的函數與基類的函數同名,但是參數不同。此時,不論有無virtual關鍵字,基類的函數將被隱藏(注意別與重載混淆)。
(2)如果派生類的函數與基類的函數同名,並且參數也相同,但是基類函數沒有virtual關鍵字。此時,基類的函數被隱藏(注意別與覆蓋混淆)。

走過路過不要錯過 下面纔是重點:
上面是截取的度娘 某c論壇的部分說明
overload+override是比較常見的,就不多說了,
針對overwirte,我寫了如下例子,外加調試,發現根本就不是這樣的

// =======================================================================================
// over()
// show override overload overwrite

class mybase {
public:
  mybase () {
  }
  virtual ~mybase () {
  }

  virtual void dosomething ( int i ) {
    std::cout << "dosomething ( int i )" << i << std::endl;
  }
  virtual void dosomething ( std::string s ) {
    std::cout << "dosomething ( std::string s )" << s << std::endl;
  }
  void dosomething ( std::vector<int>& v ) {
    for ( auto x : v )
      std::cout << "b - " << x << std::endl;
  }
};

class myderive : public mybase {
public:
  myderive () {
  }
  ~myderive () {
  }

  void dosomething ( std::string s ) {
    std::cout << "dosomething ( std::string s ) _ derive " << s << std::endl;
  }

  void dosomething ( std::vector<int>& v ) {
    for ( auto x : v )
      std::cout << "v - " << x << std::endl;
  }
};

void over () {
  mybase* p = new myderive ();
  p->dosomething ( "hello" );
  p->dosomething ( 123 );

  std::vector<int> v = { 1, 2, 3 };
  p->dosomething ( v );

  delete p;
  p = nullptr;
}


// =======================================================================================

說好的隱藏呢 在哪呢,最後不得已 上google搜索了c++ overwrite,發現根本就沒有相關的解釋,最後在stackoverflow找到了兩個比較靠譜的說法:

In C++ terminology, you have overriding (relating to virtual methods in a class hierarchy) and overloading (related to a function having the same name but taking different parameters). You also have hiding of names (via explicit declaration of the same name in a nested declarative region or scope).

The C++ standard does not use the term “overwrite” except in its canonical English form (that is, to replace one value with a new value, as in the assignment x = 10 which overwrites the previous value of x).

第二個是:
The usual distinction I’m familiar with is of overriding and overloading. Virtual functions are overridden. Functions are overloaded when there’s a version with same name but different signature (this exists in many languages). In C++ you can also overload operators.

AFAIK, overwriting is an unrelated concept (overwrite a variable, file, buffer, etc.), and is not specific to C++ or even OOP languages.

總結:overwirte不是c++的術語也不是c++的概念。
在讀本文之前 你真的分得清黑人中的奧巴馬、尼古拉斯凱奇、成龍嗎

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