奇怪的错误 C2131:表达式在 VC 2015 中未计算为常量
Strange error C2131: expression did not evaluate to a constant in VC 2015
// foo.hpp file
class foo
{
public:
static const int nmConst;
int arr[nmConst]; // line 7
};
// foo.cpp file
const int foo::nmConst= 5;
编译器 VC 2015 返回错误:
1>foo.h(7(:错误 C2131:表达式未计算为常量
1> 1>foo.h(7(:失败是由非常量参数
或 对非常量符号 1> 1>foo.h(7( 的引用: 注意:请参阅用法 "nmConst">
为什么?nmConst是静态常量,其值在*.cpp文件中定义。
可以使用
static const int
成员作为数组大小,但您必须在 .hpp 文件中的类中定义此成员,如下所示:
class foo
{
public:
static const int nmConst = 10;
int arr[nmConst];
};
这将起作用。
附言关于它背后的逻辑,我相信编译器希望在遇到类声明时立即知道数组成员的大小。如果你在类中不定义static const int
成员,编译器会明白你正在尝试定义可变长度数组并报告错误(它不会等待查看你是否真的在某个地方定义了nmconst
(。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- Visual Studio 2015:Extern "C" 和 "export" 关键字
- 递归函数计算序列中的平方和(并输出过程)
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 如何计算文件中的"columns"数?
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 使用Qt C++计算类似Git的SHA1哈希
- OpenCV C++.快速计算混淆矩阵
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++如何计算用户输入的数字中的偶数位数
- 如何计算数据类型的范围,例如int
- 类似枚举的计算常量
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 从VS 2015更新3更新到VS2015更新3 d后浮点计算行为不同的原因
- VisualStudio 2015 - 只计算命中,不停止
- 奇怪的错误 C2131:表达式在 VC 2015 中未计算为常量