简体   繁体   English

使用类与主函数相比未声明的标识符

[英]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; 应该是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. 现在,您将studentID声明为一个非静态的类成员,并且只有在构造类实例的同时声明数组编译器要求在编译时知道数组大小时,才会构造(并分配值50)。 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; 如果您写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. 在类范围之外(例如, main是在类范围之外),那么它将只是一个在编译时已知值为50的常规​​常量。

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. C ++成员数组的大小必须是constexpr在编译时就知道,简单的const不够,因为在创建类的实例时会在运行时对其进行初始化。

However, static const is enough, since you must initialize it with a constexpr, so the value is known at compile time. 但是, static const就足够了,因为您必须使用constexpr对其进行初始化,因此在编译时就知道该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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