简体   繁体   中英

In C++ what does this construction mean “InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke”?

I am a novice in C++ and don't understand this construction.

InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke

I know that & = pointer. But what does this mean?

* (InterceptionKeyStroke *)

Breaking it down:

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'

So the *(InterceptionKeyStroke*) is casting to a pointer, and then dereferencing the pointer.

I know that & = pointer.

Your knowledge is incomplete. & has multiple meanings in C++. The & you refer to is the address-of operator, as in:

int i = 0;
int* ptr = &i; // `ptr` contains address of `i`

In InterceptionKeyStroke &kstroke , the & is used to declare a reference , and only the second & , ie the one in * (InterceptionKeyStroke *) &stroke is the address-of operator I mentioned above.

But what does this mean?

 * (InterceptionKeyStroke *) 

It's a C-style cast which means that a pointer should be interpreted as if it was an InterceptionKeyStroke * . The result of that operation is then dereferenced, via the dereference operator * at the left, to get an InterceptionKeyStroke object.

So the entire InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke line is as if you told the compiler the following:

"Let kstroke be a reference to InterceptionKeyStroke, and let that reference refer to the stroke object. And yes, I know that when I take the address of stroke, then I get a pointer that doesn't technically point to an InterceptionKeyStroke. So please just interpret it as if it pointed to an InterceptionKeyStroke, because I know that it does. Now that we've established it's an InterceptionKeyStroke pointer we are talking about, dereference that pointer to obtain the object for the reference to refer to."

I should mention that this code looks very fishy. How comes stroke isn't already an InterceptionKeyStroke in the first place? What's the relationship between InterceptionKeyStroke and the type of stroke ? I have a strong feeling that you've got undefined behaviour in your program, because the C-style cast subverts the compiler's error-detection mechanism. If you lie to the compiler, then anything can happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM