【问题标题】:Strange error C2131: expression did not evaluate to a constant in VC 2015奇怪的错误 C2131:表达式在 VC 2015 中未计算为常量
【发布时间】:2015-11-10 07:54:41
【问题描述】:
// 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 文件中定义。

【问题讨论】:

    标签: c++ visual-studio-2015


    【解决方案1】:

    可以使用 static const int 成员作为数组大小,但您必须在 .hpp 文件的类中定义此成员,如下所示:

    class foo
    {
    public:
    
        static const int nmConst = 10;
        int arr[nmConst];
    
    };
    

    这会起作用。

    P.S. 关于其背后的逻辑,我相信编译器一遇到类声明就想知道数组成员的大小。如果您在类中未定义static const int 成员,编译器将理解您正在尝试定义可变长度数组并报告错误(它不会等待查看您是否真的在某个地方定义了nmconst)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      相关资源
      最近更新 更多