[英]In C++ what does this construction mean “InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke”?
我是C ++的新手,不懂這個結構。
InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke
我知道&=指針。 但是,這是什么意思?
* (InterceptionKeyStroke *)
打破它:
InterceptionKeyStroke // a type...
& // ...which is by reference
kstroke // named 'kstroke'
= // bound to (since references are bound)
* // something that a pointer points to
(InterceptionKeyStroke*) // "I know what the type is!" cast
& // address of...
stroke // ...variable named 'stroke'
所以*(InterceptionKeyStroke*)
正在轉換為指針,然后取消引用指針。
我知道&=指針。
你的知識不完整。 &
在C ++中有多重含義。 在&
你指的是地址運算符,如:
int i = 0;
int* ptr = &i; // `ptr` contains address of `i`
在InterceptionKeyStroke &kstroke
, &
用於聲明引用 ,只有第二個&
,即* (InterceptionKeyStroke *) &stroke
是我上面提到的運算符地址。
但是,這是什么意思?
* (InterceptionKeyStroke *)
它是一個C風格的強制轉換,這意味着一個指針應該被解釋為它是一個InterceptionKeyStroke *
。 然后通過左側的解除引用運算符*
取消引用該操作的結果,以獲取InterceptionKeyStroke
對象。
所以整個InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke
線就像你告訴編譯器如下:
“讓kstroke成為對InterceptionKeyStroke的引用,並讓該引用引用筆畫對象。是的,我知道當我獲取筆畫的地址時,我得到的指針在技術上並不指向InterceptionKeyStroke。所以請只是把它解釋為它指向一個InterceptionKeyStroke,因為我知道它確實如此。現在我們已經確定它是我們正在討論的一個InterceptionKeyStroke指針,取消引用指針來獲取引用的引用對象。“
我應該提一下,這段代碼看起來非常可疑。 為什么stroke
本來就不是InterceptionKeyStroke
? InterceptionKeyStroke
與stroke
類型之間的關系是什么? 我有一種強烈的感覺,你的程序中有未定義的行為,因為C風格的強制轉換顛覆了編譯器的錯誤檢測機制。 如果你撒謊到編譯器,那么任何事情都可能發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.