我试图在 C++11 标准的第 §5.1.1/8 段(第 87 页)中验证此声明(我强调的)
A nested-name-specifier that denotes a class, optionally followed by the keyword template (14.2), and then followed by the name of a member of either that class (9.2) or one of its base classes (Clause 10), is a qualified-id; 3.4.3.1 describes name lookup for class members that appear in qualified-ids. The result is the member. The type of the result is the type of the member. The result is an lvalue if the member is a static member function or a data member and a prvalue otherwise.
使用以下代码段:
#include <iostream>
namespace N {
class A {
public:
int i;
void f();
};
}
int main()
{
std::cout << &N::A::f << '\n';
std::cout << &N::A::i << '\n';
}
clang
和 gcc
编译此代码,VS2013
需要成员函数 f
的定义。
三个都打印
1
1
但我不知道这些数字是从哪里来的。
根据上面突出显示的段落,表达式 N::A::f
是纯右值,因为 f
不是静态成员函数。尽管如此,我还是能够在代码中获取它的地址。
同时,在 §5.3.1/3 中读到(强调我的):
The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. If the operand is a qualified-id naming a non-static member m of some class C with type T, the result has type “pointer to member of class C of type T” and is a prvalue designating C::m.
这给人的印象是 N::A::f
和 N::A::i
都不是左值,因为它们是 qualified-id s.
最佳答案
but I have no idea where these numbers come from.
指向成员的指针不是指针。没有 operator<<
可以输出它们的原始值,最好的 也是唯一的 匹配是输出 bool
的那个值。因此它们被转换为 bool
(这显然会产生 true
)并且输出是 1
.尝试插入 std::boolalpha
并再次检查输出。
Nonetheless, I was able to take its address in the code.
这让您感到惊讶吗?您引用了允许并解释这个确切构造的部分。它明确指出,采用命名非静态成员的限定 ID 的地址指定该成员。
qualified-id 不仅是左值或右值。这完全取决于上下文。如果他们从该成员类或其任何子类外部指定非静态成员,则它们必须是纯右值,因为它们不指定任何特定对象而是指定值(或信息,换句话说 - 类型和偏移量).
关于c++ - 合格的 id,它们是左值还是纯右值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26346386/