简体   繁体   中英

why can't I directly call a method of an instance which is accessed by pointer-to-member

For example I got a inner class:

struct Foo {
  void test() {}
};

and a outer class:

struct Bar {
  Foo foo;
};

then in main() :

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

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

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

the error about bar.*pFoo.test() is: member reference base type 'Foo Bar::*' is not a structure or union , so what's the different between bar.*pFoo.test(); and Foo foo = bar.*pFoo; foo.test(); Foo foo = bar.*pFoo; foo.test(); ?

As hinted at in the comments, .* has lower operator precedence than . .

Thus bar.*pFoo.test(); is parsed as bar.*(pFoo.test()); and is trying to access the test member of pFoo .

Since pFoo is a member pointer of type Foo Bar::* this is not a valid expression. Only class-types can appear on the left-hand side of the member access operator . (pseudo-destructor call syntax aside), which a member pointer is not.

The second example is equivalent to the expression (bar.*pFoo).test(); instead.

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