为什么我无法为c ++类中的私有变量赋值?

时间:2013-06-18 12:30:56

标签: c++ class private

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 ++不能为键赋值“错误使密钥静态”。 我不知道这意味着什么:(

1 个答案:

答案 0 :(得分: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;
};