派生类型可以与其基类的嵌套类型同名吗?

Can a derived type be the same name as a nested type of its base?

本文关键字:嵌套类型 基类 类型 派生      更新时间:2023-10-16

下面的代码合法吗?MSVC 9和g++ 4.4不一致:

struct base
{
  struct derived {};
};
struct derived : base {};
int main()
{
  typedef derived::derived type;
  return 0;
}

MSVC抱怨,混淆了类型构造函数的嵌套名称:

c:dev>cl test.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.
test.cpp
test.cpp(10) : error C2146: syntax error : missing ';' before identifier 'type'
test.cpp(10) : error C2761: '{ctor}' : member function redeclaration not allowed
test.cpp(10) : error C2065: 'type' : undeclared identifier

而g++没有:

$ g++ --version test.cpp
g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

对于上下文,我的代码包含一个名为pointer的迭代器。为了提供迭代器接口,它提供嵌套类型pointer,这是它自身的同义词。

comau认为你的代码不正确,所以我认为构造函数解释掩盖了类型解释是标准要求的1

仍然,如果您清除歧义并告诉编译器您正在尝试访问基类的derived成员,您的代码将愉快地编译:

struct base
{
  struct derived {};
};
struct derived : base {};
int main()
{
  typedef derived::base::derived type;
  return 0;
}
顺便说一下,构造函数解释盛行的事实有点道理:你有一种众所周知的方式来告诉编译器你想引用基类的内容(通过作用域解析操作符),但是你没有语法来做相反的事情(迫使编译器理解你引用的是构造函数)。因此,"默认构造函数"的行为似乎是相当合理的。
  1. 我以后可能会查,但我不保证我真的会查,这种讨厌的名字问题总是查得一团糟。

您所拥有的是名称冲突。只需将第二个结构体重命名为结构体derived2。在main()typedef derived2::derived type;中也这样做在vc++ 6.0中编译没有错误

struct base
{
  struct derived {};
};
struct derived2 : base {};

int main()
{
  typedef derived2::derived type;
  return 0;
}