具有不同范围的其他相同名称的C名称解析规则
作者:互联网
我意识到以下是可怕的风格,但为了争论,假设我有以下代码:
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是我用它初始化它?子类对象,还是自己? (最后一行中最后一个anyName引用哪个实体?它是不明确的吗?)在C规范中哪里可以解决这样的问题?
(顺便说一句,这个问题与我前几分钟发布的other question完全无关.)
解决方法:
与自己.
与您的其他问题不同,这个问题可以通过一些示例代码来解决.我将你的问题中的代码插入在线编译器(clang)……
编译器的响应非常明确:
warning: reference ‘anyName’ is not yet bound to a value when used within its own initialization
(尝试将您的孩子注释掉anyName; line;请注意,编译结果不会更改,因为编译器无论如何都找不到该对象.)
适用的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.
标签:name-lookup,c,language-lawyer 来源: https://codeday.me/bug/20190828/1746452.html