[英]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.