【问题标题】:Type Casting of Pointers to Pointers指针到指针的类型转换
【发布时间】:2020-06-15 11:56:36
【问题描述】:

我有以下元素。

p1:指向类联合的指针。

r1 类联合内的指针,指向区域类。

A.x Rectangle 类中的一个点。

Union 和 Rectangle 是基类 Region 的派生类。

我正在做以下操作。

auto p1 = new Union();
p1->r1 = new Rectangle();

现在我想改变 r1 内的一个点。

我怎样才能在指针中键入一个指针,例如我试过这个,它不起作用。

p1->(Rectangle*)r1->B.x = 6;

然而这很完美,

auto r11 = (Rectangle*)p1->r1;
r11->A.x = 1;

如何更改p1->(Rectangle*)r1->B.x = 6; 直接更改A.x 而不创建新指针?

【问题讨论】:

    标签: c++ pointers casting


    【解决方案1】:

    您需要检查运算符优先级及其关联性。 https://en.cppreference.com/w/cpp/language/operator_precedence

    正确的形式是:

    ((Rectangle*)p1->r1)->B.x = 6;
    

    更准确地说,它是这样工作的:

    1. 使用 ->(从左到右)访问 Rectangle * 成员 r1
    2. 将其转换为矩形 *(从右到左)
    3. 访问 B 成员(从左到右)。考虑到 -> 比转换 (Rectangle*) 具有更高的优先级,这就是我们在 ((Rectangle*)p1->r1) 中使用括号的原因。
    4. 通过 访问 x 成员。运营商

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2011-12-29
      • 2020-01-15
      • 1970-01-01
      • 2015-02-14
      • 2012-06-18
      • 2013-02-12
      • 1970-01-01
      相关资源
      最近更新 更多