简体   繁体   中英

undeclared identifier using class compared to main function

I want to understand why I receive a syntax error for the same syntax in different code areas.

For example:

#include<iostream>

class Grading
{
 public:
    Grading();
    ~Grading();

 private:
    //Here syntax is broken 
    //reason: undeclared Identifier 
    const int studentID = 50;
    int students[studentID];

};

int main() {
    //Here syntax is fine.
    const int studentID = 50;
    int students[studentID];
    return 0;
 }

const int studentID = 50; should be static const int studentID = 50; . Right now you are declaring studentID as a non-static class member and it will constructed (and assigned a value 50) only when class instance is constructed while to declare an array compiler requires array size to be known at compile time. Basically your code is equivalent to this:

class Grading
{
    public:
    Grading(): studentID(50) {}
    ~Grading();

 private:
    const int studentID;
    int students[studentID];
};

If you write const int studentID = 50; outside of class scope (in main for example) then it would be just a regular constant with a value 50 known at compile time.

The size of a C++ member array must be a constexpr - known at compile time, simple const is not enough, since it will be initialized at runtime, when you create an instance of the class.

However, static const is enough, since you must initialize it with a constexpr, so the value is known at compile time.

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