【问题标题】:why can't I directly call a method of an instance which is accessed by pointer-to-member为什么我不能直接调用通过指向成员的指针访问的实例的方法
【发布时间】:2019-12-02 10:04:30
【问题描述】:

例如我有一个内部类:

struct Foo {
  void test() {}
};

还有一个外部类:

struct Bar {
  Foo foo;
};

然后在main():

  Bar bar{};
  Foo Bar::* pFoo = &Bar::foo;

  bar.*pFoo.test(); // does not work

  Foo foo = bar.*pFoo;
  foo.test(); // works;

bar.*pFoo.test()的错误是:member reference base type 'Foo Bar::*' is not a structure or union,那么bar.*pFoo.test();Foo foo = bar.*pFoo; foo.test();有什么区别呢?

【问题讨论】:

  • Precedence。函数调用的排名高于取消引用。
  • @BoBTFish 谢谢,之前我真的不知道指向成员的优先级

标签: c++ pointer-to-member


【解决方案1】:

正如 cmets 中所暗示的,.* 的运算符优先级低于 .

因此bar.*pFoo.test(); 被解析为bar.*(pFoo.test()); 并试图访问pFootest 成员。

由于pFooFoo Bar::* 类型的成员指针,这不是一个有效的表达式。只有类类型可以出现在成员访问运算符 . 的左侧(伪析构函数调用语法除外),而成员指针则不是。

第二个例子等价于表达式(bar.*pFoo).test();

【讨论】:

    猜你喜欢
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 2022-11-13
    • 2016-05-03
    相关资源
    最近更新 更多