简体   繁体   English

在C ++中多次声明函数和变量

[英]Declaring functions and variables multiple times in C++

In C++, declaring a variable multiple times shows an error during compilation. 在C ++中,多次声明变量会在编译期间显示错误。 For example: 例如:

int x;
int x;

While declaring a function multiple times doesn't show any error during compilation. 在多次声明函数时,编译期间不会显示任何错误。 For example: 例如:

int add(int, int);
int add(int, int);

Why is this distinction in C++? 为什么在C ++中有这种区别?

Note that int x; 注意int x; is not (just) declaration , it's definition . 不是(只是) 声明 ,它的定义 So error arisen since ODR is violated, ie only one definition is allowed in one translation unit. 因此,由于ODR被违反而出现错误,即在一个翻译单元中仅允许一个定义。

A declaration of variable could be written as: 变量声明可以写成:

// a declaration with an extern storage class specifier and without an initializer
extern int x;
extern int x;

In the meantime int add(int, int); 在此期间int add(int, int); is a declaration (of function) exactly. 完全是一个声明(功能)。 Multiple declarations in one translation unit are fine, ODR is not violated. 一个翻译单元中的多个声明很好,不会违反ODR。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM