c++ - C++ 中的多重声明

标签 c++ c++11 language-lawyer

在 [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/

相关文章:

C++ std::vector::data 为什么返回的指针索引和 vector 索引不匹配?

c++ - 从宽到窄的字符

c++ - Qt 框架——我可以(合法地)使用 qmake 而不是 Qt 创建商业应用程序吗?

c++ - 创建一个包含要绘制的项目的类(段错误)

c++ - "float = float - float"中是否存在隐式类型提升?

vba - VBA CVar 函数什么时候真正有用?

c++ - clang tidy pro 类型成员 init resharper

c++ - 具有自定义值类型的 map::emplace()

c++ - gcc 4.8 或更早版本对正则表达式有问题吗?

C++ 标准 : end of lifetime