簡體   English   中英

這個C ++聲明是什么意思?

[英]What does this C++ declaration mean?

我正在為一個類創建一個類圖,該類在其頭文件中有許多與此類似的定義。

  1       2                                        3             4       5
const std::pair<Controller<_Tp,_Val>*, _Val>& getHighestBidder(_Tp obj) const;

我知道他們中的幾個人做了什么,

2) says that this method will return a std::pair<Controller<_Tp, _Val>*, _Val>
3) gives the name of the function
4) defines the type of object this function accepts as a parameter

但是,1和5是什么意思?

任何幫助/指針都會很棒。 謝謝

首先,請注意它沒有返回std::pair<Controller<_Tp, _Val>*, _Val> ,它返回一個std::pair<Controller<_Tp, _Val>*, _Val> & ,即對這樣的引用已存在的對象。

(1)表示它是對象的const引用; 你不能通過這個引用修改對象。

(5)表示這是一個const成員函數,即它不會修改它被調用的對象。

它意味着完全一樣,但我更喜歡把它寫成:

  1                                      2       3              4          5
std::pair<Controller<_Tp,_Val>*, _Val> const& getHighestBidder(_Tp obj) const;


A member function
   5: const member function
   4: Taking a parameter of type _Tp by value
   3: With a function name getHighestBidder
Returning
   2: A const reference
   1: To a std::pair<>
      1a: first  member has type Controller<_Tp,_Val>*
      1b: second member has type _Val


5: Means calling this method will not change the state of the object
2: Means the returned object can not be altered via the reference returned
   This is probably because it is an alias of an internal member and if you
   could alter the object you would invalidate the const mention at (5).

(1)表示返回的對象是const引用,您只能調用它引用的對象的const方法。

(5)意味着該方法是const:您可以使用const引用或指針調用它(並且它不能修改和成員)。

  1. 表示返回類型是常量(即不能修改)
  2. 意味着該方法不能修改它所屬的類的任何成員變量

有關詳細說明,請參閱:

在函數返回值中使用'const'

Messier Still - 面向對象編程

在以下鏈接中:

http://duramecho.com/ComputerInformation/WhyHowCppConst.html

當你將“const”添加到變量/類聲明時,它會使編譯器不可變,類似於objective-c中的“define”特性。 它非常有用,因為它會產生錯誤,通常只會使編譯器崩潰到編譯器可以捕獲的錯誤中(因為您試圖更改常量的值)。

const int randomInteger = 5;
randomInteger = 3;

你看,這會返回一個錯誤,這使調試更容易。

“const”的一個很好的網絡資源在這里:

http://duramecho.com/ComputerInformation/WhyHowCppConst.html

暫無
暫無

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

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