[英]Why can't you get pointer-to-member from unqualified member function name in C++11?
[英]why can't I directly call a method of an instance which is accessed by pointer-to-member
例如我有一个内部类:
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();
之间有什么不同bar.*pFoo.test();
和Foo foo = bar.*pFoo; foo.test();
Foo foo = bar.*pFoo; foo.test();
?
正如评论中所暗示的, .*
运算符优先级低于.
.
因此bar.*pFoo.test();
被解析为bar.*(pFoo.test());
并试图访问pFoo
的test
成员。
由于pFoo
是Foo Bar::*
类型的成员指针,因此这不是一个有效的表达式。 只有类类型可以出现在成员访问运算符的左侧.
(伪析构函数调用语法除外),成员指针不是。
第二个例子等价于表达式(bar.*pFoo).test();
反而。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.