由于指定的标准int a
属于简单declaration
.其实
simple-declaration:
decl-specifier-seq_opt init-declarator-list_opt ; //
attribute-specifier-seq decl-specifier-seq_opt init-declarator-list ;
type-specifier:
trailing-type-specifier //
class-specifier
enum-specifier
trailing-type-specifier:
simple-type-specifier //
elaborated-type-specifier
typename-specifier
cv-qualifier
simple-type-specifier:
nested-name-specifieropt type-name
nested-name-specifier template simple-template-id
char
char16_t
char32_t
wchar_t
bool
short
int //
long
signed
unsigned
float
double
void
auto
decltype-specifier
Run Code Online (Sandbox Code Playgroud)
因此int a
是一个简单的声明.但是,如果我们重新声明a
与以下相同的范围:
int a;
int a;
Run Code Online (Sandbox Code Playgroud)
我们有
test.cpp:4:5: error: redefinition of ‘int a’
test.cpp:3:5: error: ‘int a’ previously declared here
Run Code Online (Sandbox Code Playgroud)
到底究竟int a
是什么?
从标准
A declaration is a definition unless it declares a function without specifying the function’s body
Run Code Online (Sandbox Code Playgroud)
a
不是方法,所以int a
意味着声明和定义.如果您在单个翻译单元中多次定义名称,则违反了一个定义规则,因此错误.
编辑
为澄清,我发布整段:
声明是一个定义,除非它声明一个函数而没有指定函数的主体(8.4),它包含extern说明符(7.1.1)或者链接规范(27)(7.5),既不是初始化者也不是函数体,它在类定义(9.4)中声明了一个静态数据成员,它是一个类名声明(9.1),或者它是一个typedef声明(7.1.3),一个using声明(7.3.3),或者是一个使用 - 指令(7.3.4).