C++这种结构"InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke"意味着什么?

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

本文关键字:InterceptionKeyStroke stroke 什么 意味着 kstroke 结构 C++      更新时间:2023-10-16

我是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 的引用,并让该引用引用 stroke 对象。是的,我知道当我获取笔画地址时,我得到的指针在技术上并不指向拦截键。因此,请将其解释为好像它指向拦截击键,因为我知道它确实如此。现在我们已经确定它是我们正在谈论的拦截击键指针,取消引用该指针以获取引用的对象。

我应该提到这段代码看起来很可疑。为什么stroke一开始就不是InterceptionKeyStrokeInterceptionKeyStrokestroke类型之间有什么关系?我有一种强烈的感觉,你的程序中有未定义的行为,因为 C 风格的强制转换破坏了编译器的错误检测机制。如果你对编译器撒谎,那么任何事情都可能发生。

相关文章:
  • 没有找到相关文章