2013-06-18 32 views
-2
using namespace std; 

class Student{ 
    public: 
     Student(int test) 
     { 
      if(test == key) 
      {cout << "A student is being verified with a correct key: "<< test << endl;} 
     } 
     private: 
     int key= 705; 
}; 



int main() 
{ 
    int testkey; 
    cout << "Enter key for Bob: "; 
    cin >> testkey; 

    Student bob(testkey); 
} 

所以我試圖運行它,但它說C++不能分配鍵值「Error making key static」。 我不知道這意味着什麼:(爲什麼我無法賦值給C++類中的私有變量?

+0

@LuchianGrigore但它的作品在我GCC,什麼是錯,此代碼 – johnchen902

+0

我真的很新的節目能否請你指出在句法出了錯或?。應該怎麼做纔對? 我相信你會得到什麼我正在試着去做。它不適用於代碼塊 – user2477112

+0

需要啓用C++ 11以使'int key = 705;'在類聲明中工作。 – billz

回答

1

你不能在C++ 03類中的變量賦值這樣,但C++ 11(見herehere)。

但是,你要做到這一點像構造:

class Student{ 
public: 
    Student(int test) 
    : key(705) { 
    // ^^^^^^^^ 

    // or if you want to init it with the parameter test 
    // key(test) { 

     if(test == key) 
     {cout << "A student is being verified with a correct key: "<< test << endl;} 
    } 
private: 
    int key; 
}; 
+0

嗯不知道。非常感謝!它的工作原理 – user2477112

+2

您可以在聲明時初始化非靜態數據成員,而不是在C++ 03中。 – juanchopanza

+0

@ juanchopanza感謝您的意見。我更新了我的答案。 – user1810087

相關問題