C++ 指向布尔值的指针

use*_*492 5 c++ pointers boolean

我在尝试实现一个包含指向布尔值的指针的类时遇到问题...

class BoolHolder {
    public:
    BoolHolder(bool* _state);

    bool* state;
}

BoolHolder::BoolHolder(bool* _state) {
    state = _state;
}

bool testbool = false;

BoolHolder testbool_holder( &testbool );
Run Code Online (Sandbox Code Playgroud)

如果我这样做,testbool_holder.state 总是报告它是真的,不管 testbool 本身是真还是假

我究竟做错了什么?我只是希望该类能够为 testbool 维护一个最新的值,但我不知道如何实现这一点。谢谢

Nei*_*irk 6

testbool_holder.state 如果 state 不是空指针,则返回 true

*(testbool_holder.state) 返回状态指向的布尔值

试试这个以获得更多的 C++ 解决方案

class BoolHolder
{
public:
    BoolHolder(bool* state) : state(state) {}
    bool GetState() const { return *state; } // read only
    bool& GetState() { return *state; } // read/write

private:
    bool* state;
}

bool testbool = false;
BoolHolder testbool_holder(&testbool);
if (testbool_holder.GetState()) { .. }
Run Code Online (Sandbox Code Playgroud)

如果您只想允许读取访问(并且可能将指针更改为const bool *),请删除第二个 getter如果您想要两者,那么您需要两个 getter。(这是因为读/写不能用于读取 const 对象)。