C++ 指向布尔值的指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18559572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:01:48  来源:igfitidea点击:

C++ pointer to boolean value

c++pointersboolean

提问by user2737492

I'm having problems trying to implement a class which contains a pointer to a boolean...

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

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

    bool* state;
}

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

bool testbool = false;

BoolHolder testbool_holder( &testbool );

If I do this, testbool_holder.state always reports that it is true, no matter whether testbool itself is true or false

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

What am I doing wrong? I just want the class to be able to maintain an up to date value for testbool but I don't know how to effect this. Thanks

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

回答by Neil Kirk

testbool_holder.statereturns true if state is not a null pointer

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

*(testbool_holder.state)returns the value of the bool pointed to by state

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

Try this for a more C++ solution

试试这个以获得更多的 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()) { .. }

Remove the second getter if you only want to allow read access (and maybe change the pointer to const bool *) If you want both, then you need both getters. (This is because read/write can't be used to read on a const object).

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

回答by Hrishi

It's right. What you have is not the value of the boolean but a pointer to the boolean. You must dereference the pointer to obtain the value of the bool itself. Since you have a pointer, it will contain an address which is an integer. Since in C and C++ all non zero integers are true, you will get true.

这是正确的。您拥有的不是布尔值,而是指向布尔值的指针。您必须取消引用指针才能获得 bool 本身的值。由于您有一个指针,它将包含一个整数地址。因为在 C 和 C++ 中所有非零整数都是真的,你会得到真的。