[英]Why can't I use static_cast<int&> to pass an integer reference parameter to a function in C++?
我在C ++程序中有一個枚舉參數,我需要使用一個通過參數返回值的函數來獲取該參數。 我首先將其聲明為int,但在代碼審查時要求將其鍵入為枚舉(ControlSource)。 我做了這個,但它打破了Get()函數 - 我注意到一個C樣式轉換為int並解決了問題,但是當我第一次嘗試使用static_cast <>修復它時,它沒有編譯。
為什么會這樣,為什么當eTimeSource是一個int時,根本不需要轉換來通過引用傳遞整數?
//GetCuePropertyValue signature is (int cueId, int propertyId, int& value);
ControlSource eTimeSource = ControlSource::NoSource;
pPlayback->GetCuePropertyValue(programmerIds.cueId, DEF_PLAYBACKCUEPROPERTY_DELAY_SOURCE, static_cast<int&>(eTimeSource)); //This doesn't work.
pPlayback->GetCuePropertyValue(programmerIds.cueId, DEF_PLAYBACKCUEPROPERTY_DELAY_SOURCE, (int&)(eTimeSource)); //This does work.
int nTimeSource = 0;
pPlayback->GetCuePropertyValue(blah, blah, nTimeSource); //Works, but no (int&) needed... why?
當您將變量轉換為不同類型的值時,您將獲得一個臨時值,該值不能綁定到非常量引用:修改臨時值是沒有意義的。
如果您只需要讀取值,則常量引用應該沒問題:
static_cast<int const &>(eTimeSource)
但您也可以創建一個實際值,而不是引用:
static_cast<int>(eTimeSource)
static_cast<int&>((eTimeSource))); //This doesn't work.
是的,它不起作用,因為eTimeSource
不是一個int
所以你不能綁定一個int&
它。
(int&)((eTimeSource))); //This does work.
錯了,這也不起作用,它似乎只是。 C風格的演員陣容歸於編譯器,並說“只要把它變成這種類型,即使這不合法”。 僅僅因為編譯的東西並不意味着它有效。
為什么當
eTimeSource
是一個int
根本不需要轉換來通過引用傳遞整數?
因為您可以將int&
int
綁定到不同的類型,而eTimeSource
是不同的類型。 一個int&
是一個參考int
。 如果你可以將它綁定到不同的類型,它就不會引用int
,不是嗎?
如果代碼審閱者說要將變量更改為枚舉類型,那么他們可能還意味着您需要更改函數參數以獲取ControlSource&
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.