在 [basic.scope.declarative]p4 中,阅读
Given a set of declarations in a single declarative region, each of which specifies the same unqualified name, — (4.1) they shall all refer to the same entity …
天真的阅读可能意味着以下代码可能是有效的,因为“两个声明都引用同一个实体”:
int x;
int x;
然后人们可能会记得一个定义规则 [basic.def.odr]p1。上述推理可能仅适用于声明而不适用于定义。 [basic.def]p2 中详细说明了区别。例如下面的代码肯定是有效的:
extern int x;
extern int x;
[basic.def]p2 中的最后一个示例表明以下代码应该有效,但它无法编译(使用 MSVC2015)。
struct B
{
int y;
};
struct D : B
{
using B::y;
using B::y;
};
问题出在哪里?
错误信息是
the using-declaration for 'B::y' cannot co-exist with the existing using-declaration for 'B::y'
最佳答案
这个来自 [namespace.udecl]p10 的例子和你的完全一样:
struct B {
int i;
};
struct X : B {
using B::i;
using B::i; // error: double member declaration
};
错误由 [class.mem]p1 备份:
A member shall not be declared twice in the member-specification, except that a nested class or member class template can be declared and then later defined, and except that an enumeration can be introduced with an opaque-enum-declaration and later redeclared with an enum-specifier.
所以您走在正确的轨道上。多个声明是可以的,只要它们不违反其他规则(例如一个定义、成员规范等)
例如,以下是可以的:
struct X;
struct X;
或者更复杂的例子:
struct X
{
struct A;
struct A
{
int y;
};
};
struct X;
struct X::A;
关于c++ - C++ 中的多重声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31713682/