c++ - 成员(member)名查找规则

标签 c++ class language-lawyer

秒。 10.2 描述成员名称查找规则:

10.2/3:

The lookup set for f in C, called S(f, C), consists of two component sets: the declaration set, a set of members named f; and the subobject set, a set of subobjects where declarations of these members (possibly including using-declarations) were found. In the declaration set, using-declarations are replaced by the members they designate, and type declarations (including injected-class-names) are replaced by the types they designate. S(f, C) is calculated as follows:

10.2/4:

If C contains a declaration of the name f, the declaration set contains every declaration of f declared in C that satisfies the requirements of the language construct in which the lookup occurs.

考虑以下两个示例:

class A
{
    void foo(){ A::a; } //S(a, A)={ static const int a; }
    static const int a = 5;
}

class A
{
    int b[A::a]; //S(a, A) is empty and the program is ill-formed
    static const int a = 5;
}

实际的 S(f, C) 计算规则是什么,为什么?

最佳答案

对于这些代码片段

class A
{
    void foo(){ A::a; } //S(a, A)={ static const int a; }
    static const int a = 5;
};

class A
{
    int b[A::a]; //S(a, A) is empty and the program is ill-formed
    static const int a = 5;
};

您应该考虑标准的 3.4 名称查找 部分中描述的名称查找。它们与您引用的引语没有任何共同之处。尽管我可以在第一类定义中为名称 A::a 显示 S(f, C) 是什么。所以 S( a, A ) 仅来自一个声明 static const int a = 5

请注意,在第二个类定义中将找不到名称 A::a,因为它必须在使用前声明。

另一个规则用于成员函数中的名称查找。在第一个类定义名称 A::a 中将找到。

正如我所指出的,所有这些都在标准的第 3.4 节中进行了描述。

至于你引用的短语,那么更合适的例子将是例如以下

struct A
{
   void f( int );
};

struct B : A
{
   using f;
   void f( char );
};

在这种情况下,如果搜索名称 f,则 S( f, B ) 将包含两个声明

using f; // or void f( int );

void f( char );

关于c++ - 成员(member)名查找规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24293917/

相关文章:

c++如何将名称传递给基类的构造函数

c++ - UINT_MAX 是否所有位都设置为 1?

c++ - GetLogicalDrives 加上附加信息 C++

c++ - 这个结构怎么会有 sizeof == 0?

python - 在 Python 中定义一个类

php - 如何在 PHP 中获取特定类的实例?

c++ - Qt qrc 资源路径不起作用

c++ - 为什么在unordered_map中使用find()比直接读取要快很多?

c++ - 我不明白 [dcl.enum]/4 与下面突出显示的 "enclosing enum specififer"相关的内容

c++ - 带有 std::enable_if 和 std::is_default_constructible 的 SFINAE 用于 libc++ 中的不完整类型