[英]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.