我有一个正在处理的C / C ++混合项目。我有一个全局常量C代码,希望能够从我的C ++脚本和C脚本访问。在这种特殊情况下,我试图使用具有可变尺寸的C ++数组,这些尺寸由C全局常数代码中定义的常数整数组成。但是,当我尝试使用或声明此数组时,出现以下错误:数组维数不是整数常量(尽管我在C代码中将它们定义为整数常量)。
常数
const int x = 5;
Run Code Online (Sandbox Code Playgroud)
常数h
#ifdef __cplusplus
extern "C" {
#endif
extern const int x;
#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)
my_cpp.h
#include "constants.h"
Run Code Online (Sandbox Code Playgroud)
my_cpp.cpp
#include "my_cpp.h"
double A[x];
Run Code Online (Sandbox Code Playgroud)
所以在这里,我会得到一个错误,指出x不是整数常量。我哪里做错了?
您没有x在头文件中放置的定义,因此它不是核心常量表达式。
最简单的修复方法是const int x = 5;在头文件中使用。另外,您可以使用enum:enum { x = 5; }-这给您真正的prvalue,非常类似于文字5本身。
有关什么是C ++中的常量表达式(数组索引必须是C ++中的常量表达式)的更多信息,请参见以下网址:https : //en.cppreference.com/w/cpp/language/constant_expression
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |