简体   繁体   中英

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; 

Compiler VC 2015 return error:

1>foo.h(7): error C2131: expression did not evaluate to a constant
1> 1>foo.h(7): failure was caused by non-constant arguments or
reference to a non-constant symbol 1> 1>foo.h(7): note: see usage of 'nmConst'

Why? nmConst is static constant with value defined in *.cpp file.

It's possible to use static const int member as an array size, but you'll have to define this member within class in your .hpp file like so:

class foo
{
public:

    static const int nmConst = 10;
    int arr[nmConst];

};

This will work.

PS About the logic behind it, I believe compiler wants to know size of the array member as soon as it encounters class declaration. If you leave static const int member undefined within the class, compiler will understand that you're trying to define variable-length array and report an error (it won't wait to see if you actually defined nmconst someplace).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM