[英]undeclared identifier using class compared to main function
我想了解为什么我在不同的代码区域收到相同语法的语法错误。
例如:
#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;
应该是static const int studentID = 50;
。 现在,您将studentID
声明为一个非静态的类成员,并且只有在构造类实例的同时声明数组编译器要求在编译时知道数组大小时,才会构造(并分配值50)。 基本上,您的代码与此等效:
class Grading
{
public:
Grading(): studentID(50) {}
~Grading();
private:
const int studentID;
int students[studentID];
};
如果您写const int studentID = 50;
在类范围之外(例如, main
是在类范围之外),那么它将只是一个在编译时已知值为50的常规常量。
C ++成员数组的大小必须是constexpr
在编译时就知道,简单的const
不够,因为在创建类的实例时会在运行时对其进行初始化。
但是, static const
就足够了,因为您必须使用constexpr对其进行初始化,因此在编译时就知道该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.