c++ - 代码块和 g++ 错误 "is private"

标签 c++ c++11 g++ codeblocks

我在使用代码块 IDE(使用 g++ 编译器)时遇到了这些错误 每个成员变量都是“私有(private)的”。据我所知,在其他成员中使用私有(private)变量是唯一合法的,这就是我正在做的。这是我的 cpp 的代码:

/*
bullsAndCows.cpp
*/

using namespace std;

//enum class state {_bull, _cow, _none};

class bullsAndCows {
private:
    const int m_size{4};
    bool m_guessed{false};
    std::vector<char> m_digit;
    std::vector<state> m_digitState;

public:
    bullsAndCows() {
        m_guessed = false;
        for(int i = 0; i < m_size; i++)
            m_digitState[i] = state._none;
    }

    void bullsAndCows::setGuessed(bool value) { _guessed = value; }
    bool bullsAndCows::getGuessed() { return _guessed; }
    void bullsAndCows::setDigit(char value, int i) { m_digit[i] = value; }
    char bullsAndCows::getDigit(int i) { return m_digit[i]; }
    void bullsAndCows::setDigitState(state value, int i) { m_digitState[i] = value; }
    state bullsAndCows::getDigitState(int i) { return m_digitState[i]; }
};

这是我正在测试的主要代码:

#include "bullsAndCows.h"

using namespace std;

int main()
{
    bullsAndCows game;
    for(int i = 0; i < game.m_size; i++) {
        cin >> game.m_digit[i];
        cout << game.m_digit[i];
    }

    return 0;
}

编译器上激活了 c++11 标志。

最佳答案

编译器是正确的。
声明:

cin >> game.m_digit[i];

正在访问私有(private)成员:

class bullsAndCows {
private:
    const int m_size{4};
    bool m_guessed{false};
    std::vector<char> m_digit;
    std::vector<state> m_digitState;

私有(private)成员只能被类内部的方法访问,不能被外部实体访问,比如 main 函数。

您的选择是:

  • 创建 getter 和 setter 方法。
  • 为类 bullsAndCows 重载流提取运算符>>
  • 公开变量。

关于c++ - 代码块和 g++ 错误 "is private",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28200004/

相关文章:

c++ - 修改 makefile

c++ - VS 2017错误C2664 map 插入尝试

c++ - std::copy 用于多维数组

c++ - const 迭代器的模板参数而不是迭代器

c++ - GNU g++编译器下main()的返回类型

c++ - std :shared_ptr in libstdc++ correct 的原子交换是怎样的

c++ - ucnv_open 错误 U_FILE_ACCESS_ERROR

C++ 继承 : scoping and visibility of members

c++ - 这个语法是什么意思, `class template <class R, class ...Args> class name<R(Args...)>`

c++ - 检查一个 vector 是否包含另一个 vector 的子字符串