是否可以在不定义整数的情况下声明类似整数的东西?
在C++中,可以将函数的定义和声明分开。
// foo.cpp
int foo(int);
int foo(int a) {
return 45;
}
但是对于非功能,它似乎不是
// bar.cpp
int bar;
int bar = 10;
bar.cpp
产生这个
$ clang++ -c bar.cpp
bar.cpp:2:5: error: redefinition of 'a'
int a = 10;
^
bar.cpp:1:5: note: previous definition is here
int a;
^
1 error generated.
在第二条语句上省略类型注释会产生不同的错误。
// bar2.cpp
int bar;
bar = 10;
生产
$ clang++ -c bar2.cpp
bar2.cpp:3:1: error: C++ requires a type specifier for all declarations
bar = 10;
^
1 error generated.
extern int bar; // declares, but does not define bar
int bar = 10; // defines bar
请注意,这要求bar
具有静态存储持续时间。下面是一个用法示例。
#include <iostream>
int main()
{
extern int bar;
std::cout << bar; // this should print 10
}
int bar = 10;