具有不同范围的其他相同名称的 C++ 名称解析规则
C++ name resolution rules for otherwise identical names with different scope
我意识到以下是可怕的风格,但为了论证,假设我有以下代码:
struct parent
{
virtual ~parent() {}
};
struct child : public parent
{
child() {}
virtual ~child() {}
};
struct anotherClass
{
static parent& anyName;
};
child anyName; // create an instance of 'child'
parent& anotherClass::anyName = anyName; // create a parent-class ref to the child object
当我用 anyName
初始化上面的 anotherClass::anyName
引用时,我用哪个 anyName
初始化它? child-class 对象,还是自身? (最后一行中的最后一个 anyName
指的是哪个实体?是否有歧义?)在 C++ 规范中的什么地方会解决这样的问题?
(顺便说一句,这个问题与我几分钟前发布的 完全无关。)
自带.
与您的其他问题不同,这个问题可以通过一些示例代码来解决。我将你问题中的代码插入在线编译器 (clang) ...
编译器的响应很清楚:
warning: reference 'anyName' is not yet bound to a value when used within its own initialization
(尝试注释掉你的 child anyName;
行;注意编译结果不会改变,因为编译器无论如何都找不到那个对象。)
适用的 C++ 标准规则在 [basic.lookup.unqual]
中:
A name used in the definition of a static data member of class X
(after the qualified-id of the static member) is looked up as if the name was used in a member function of X
.
来自[basic.scope.pdecl]
The point of declaration for a name is immediately after its complete declarator and before its initializer (if any), except as noted below.
这两个规则一起确保初始化器对 anyName
的非限定查找找到 anotherClass::anyName
.
我意识到以下是可怕的风格,但为了论证,假设我有以下代码:
struct parent
{
virtual ~parent() {}
};
struct child : public parent
{
child() {}
virtual ~child() {}
};
struct anotherClass
{
static parent& anyName;
};
child anyName; // create an instance of 'child'
parent& anotherClass::anyName = anyName; // create a parent-class ref to the child object
当我用 anyName
初始化上面的 anotherClass::anyName
引用时,我用哪个 anyName
初始化它? child-class 对象,还是自身? (最后一行中的最后一个 anyName
指的是哪个实体?是否有歧义?)在 C++ 规范中的什么地方会解决这样的问题?
(顺便说一句,这个问题与我几分钟前发布的
自带.
与您的其他问题不同,这个问题可以通过一些示例代码来解决。我将你问题中的代码插入在线编译器 (clang) ...
编译器的响应很清楚:
warning: reference 'anyName' is not yet bound to a value when used within its own initialization
(尝试注释掉你的 child anyName;
行;注意编译结果不会改变,因为编译器无论如何都找不到那个对象。)
适用的 C++ 标准规则在 [basic.lookup.unqual]
中:
A name used in the definition of a static data member of class
X
(after the qualified-id of the static member) is looked up as if the name was used in a member function ofX
.
来自[basic.scope.pdecl]
The point of declaration for a name is immediately after its complete declarator and before its initializer (if any), except as noted below.
这两个规则一起确保初始化器对 anyName
的非限定查找找到 anotherClass::anyName
.