代码块和 G++ 错误"is private"

code blocks and g++ error "is private"

本文关键字:is private 错误 G++ 代码      更新时间:2023-10-16

我在代码块中遇到这些错误 IDE(使用 g++ 编译器)每个成员变量的"是私有的"。据我所知,在其他成员中使用私有变量是合法的,这就是我正在做的事情。这是我的 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];

正在访问私有成员:

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

私有成员只能通过类内的方法访问,而不能由外部实体(如 main 函数)访问。

您的选择是:

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