C++:如何在不定义的情况下声明非函数?
C++: how to declare non-function without defining it?
是否可以在不定义整数的情况下声明类似整数的东西?
在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;
相关文章:
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- 在没有标识符的情况下如何读取复杂的C++类型声明?
- 如何在不为其声明变量的情况下获取和使用常量值的地址?
- 为什么在这种情况下,前向声明不起作用?
- 如何在不混淆字段的情况下声明复数?
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 在C++我可以在不在本地声明结构的情况下将结构作为指针传递吗?
- C++:如何在不定义的情况下声明非函数?
- 我需要在不使用前向声明的情况下相互包含两个头文件,导致"incomplete type"错误
- 在不使用默认构造函数的情况下声明 POD 结构时,会实例化什么?
- 有什么理由在没有继承的情况下声明一个虚拟方法
- 如何在不初始化常量的情况下声明数组?
- 如何在不包含 Windows.h 的情况下获取 IsDebuggerPresent 的声明
- 如何在不指定 C++ 中的所有参数的情况下声明程序的 main() 入口点
- 如何在不指定模板类型的情况下声明通用抽象类的对象
- 在C++中,如何在没有新元素且不单独声明单个元素的情况下创建"std::initializer_list<base *>"?
- 有没有办法在不引用其模板类型的情况下转发声明指向类的指针
- 如何在不依赖#Define的情况下转发声明数组大小
- C++。可以在没有错误的情况下执行此操作:"未在此范围内声明"
- 在不键入别名类型的完整声明的情况下,无法从类模板定义中访问类型的类型别名