簡體   English   中英

關於 C++ 中的重載成員函數的問題?

[英]Question about overloaded member functions in C++?

我正在從地址https://cs.senecac.on.ca/~chris.szalwinski/archives/btp200.081/content/overl.ZFC336EZ883.8 在第一行,他們說:

成員 function 的簽名包括:

  • function 名稱,

  • 其參數的數據類型,

  • 參數的順序和
    可能

  • function 的 const 狀態。

我不明白他們所說的“function 的 const 狀態”是什么意思。

有人可以詳細說明一下嗎? 謝謝。

在 C++ 中,您可以將 class 的成員 function 聲明為const ,方法是將該關鍵字附加到其簽名(例如, int MyClass:doSomething(int param) const {...} myClass:do)。 Doing so guarantees that the function won't change the (non- mutable ) members of the class object on which the function is called - and hence it can be called with const instances of that class.

class 允許有兩個不同的成員函數,其簽名的不同之處僅在於它們是否聲明為const

它們的意思是總結功能必須不同的項目才能放入相同的 class scope。 最后的const是:

struct A {
  void f();
  void f() const;
};

這些是有效的重載。 如果您在A上調用f ,則調用第一個,如果您在const A上調用它,則使用第二個:

A a;
a.f(); // takes first

A const& b = a;
b.f(); // takes second

請注意,此處誤用了“簽名”一詞。 function 的簽名更廣泛,還包括 class,其中 function 是其中的成員。 簽名唯一標識 function。

將成員 function 聲明為const會告訴編譯器成員 function 不會修改對象的數據,也不會調用非 const 的其他成員函數。

編譯器將檢查以確保您確實沒有修改數據。 You can call a const member function for either a const or a non-const object, but you can't call a non-const member function for a const object (because it could modify the object).

您可以在此處閱讀有關 C++ 中的 constness 的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM