派生类型可以与其基类的嵌套类型同名吗?
Can a derived type be the same name as a nested type of its base?
下面的代码合法吗?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;
}
顺便说一下,构造函数解释盛行的事实有点道理:你有一种众所周知的方式来告诉编译器你想引用基类的内容(通过作用域解析操作符),但是你没有语法来做相反的事情(迫使编译器理解你引用的是构造函数)。因此,"默认构造函数"的行为似乎是相当合理的。
- 我以后可能会查,但我不保证我真的会查,这种讨厌的名字问题总是查得一团糟。
您所拥有的是名称冲突。只需将第二个结构体重命名为结构体derived2
。在main()
和typedef derived2::derived type;
中也这样做在vc++ 6.0中编译没有错误
struct base
{
struct derived {};
};
struct derived2 : base {};
int main()
{
typedef derived2::derived type;
return 0;
}
相关文章:
- C++ 在外部使用嵌套结构实现类函数
- CRTP:为什么获得嵌套类型和派生类的嵌套方法有区别
- 为什么嵌套类型的基类不需要"typename"?
- 嵌套抽象基类的泛型模板
- 此嵌套模板基类是否不明确?
- 如何在模板类中使用嵌套的结构/类类型作为返回值
- 如何在C++中的另一个模板函数中使用属于模板化类的嵌套类型?
- 具有嵌套类型的类的概念
- 将嵌套类型的类分开为标题和源
- 如何定义一个模板类函数,该函数在类外的签名中具有嵌套类型的模板参数
- 嵌套类型:结构与类
- 将类型的嵌套类型引用为类模板的参数的问题
- 为什么我们不能通过类成员访问表达式使用嵌套类型?
- 嵌套类型作为基类的模板参数
- 派生类型可以与其基类的嵌套类型同名吗?
- 在c++中(在编译时)是否有办法强制派生类定义嵌套类型?
- Cython:公开带有嵌套类型定义的c++类
- 使用模板类的嵌套类型作为模板参数
- C++类中嵌套类型的快捷方式
- 嵌套在模板类定义中的C++模板类型