【问题标题】:Why am I unable to assign value to a private variable in c++ class? [closed]为什么我无法为 c++ 类中的私有变量赋值? [关闭]
【发布时间】:2013-06-18 12:30:55
【问题描述】:
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++ 无法为键分配值“错误使键成为静态”。 我不知道这是什么意思:(

【问题讨论】:

  • @LuchianGrigore 但它适用于我的 GCC,这段代码有什么问题?
  • 我对编程真的很陌生。您能否指出语法错误的地方或应该做些什么来使它正确?我相信你会得到我想要做的。它不适用于代码块
  • 需要启用 C++11 以使 int key= 705; 在类声明中工作。
  • “将密钥设为静态时出错”不是您收到的错误消息。肯定有比这更多的词。
  • @user2477112 我愿意。显然你没有明白我的意思是你应该从一本书中学习,而不是仅仅抛出代码并期望它能够工作,而不了解基础知识。

标签: c++ class private


【解决方案1】:

In class member initializers 是 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;
};

【讨论】:

  • 嗯不知道。太感谢了!成功了
  • 你可以在声明时初始化非静态数据成员,只是在 C++03 中不行。
  • @juanchopanza 感谢您的建议。我更新了我的答案。
猜你喜欢
  • 2018-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 2016-09-29
  • 2021-09-14
  • 1970-01-01
相关资源
最近更新 更多