簡體   English   中英

使用類與主函數相比未聲明的標識符

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM