demo :
#include<iostream>
struct A { int i = 10; };
struct B : A { };
int main(){
std::cout << "decltype(&B::i) == int A::* ? " << std::boolalpha
<< std::is_same<decltype(&B::i), int A::*>::value << '\n'; //#1
A a;
std::cout << a.*(&A::i) << '\n';
std::cout << "decltype(&B::i) == int B::* ? "
<< std::is_same<decltype(&B::i), int B::*>::value << '\n'; //#2
B b;
std::cout << b.*(&B::i) << '\n';
}
代码打印
decltype(&B::i) == int A::* ? true
10
decltype(&B::i) == int B::* ? false
10
我使用了 [expr.unary.op]/3 中的示例,其中标准说 &B::i
的类型是 int A::*
,但这不是规范的。
最佳答案
从您链接到的段落中,强调我的:
If the operand is a qualified-id naming a non-static or variant member
m
of some classC
with typeT
, the result has type “pointer to member of classC
of typeT
” and is a prvalue designatingC::m
.
"Some class C
"意味着它不需要与 qualified-id 提到的类相同。在这种情况下,i
是 A
的成员,即使被 &B::i< 命名,它仍然是
。因此A
的成员&B::i
的类型是int A::*
,可以通过测试验证
std::is_same<decltype(&B::i), int A::*>::value
根据 [class.qual]/1 , 成员查找遵循 [class.member.lookup] 中详述的算法.根据那里的规则,检查成员 i
来自的子对象,确定类 C
。由于i
是子对象A
的成员,所以指向成员的指针的类被确定为A
。
关于c++ - 您如何使用标准引号解释指向基类和派生类成员的指针的这种差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56619345/