为什么我不能赋值给一个私有变量在c++类

Why am I unable to assign value to a private variable in c++ class?

本文关键字:一个 变量 c++ 不能 赋值 为什么      更新时间:2023-10-16
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++不能给键赋值"错误使键静态"。我不知道这是什么意思

In类成员初始化器是c++ 11的一个特性,否则你必须在构造函数中初始化它。

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