指向布尔值的C ++指针 [英] C++ pointer to boolean value

查看:273
本文介绍了指向布尔值的C ++指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 );

如果我这样做,则无论testbool本身是对还是错,testbool_holder.state都会始终报告它为真

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

我做错了什么?我只希望该类能够维护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_holder.state如果状态不是空指针,则返回true

testbool_holder.state returns true if state is not a null pointer

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

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

尝试此操作以获得更多的C ++解决方案

Try this for a more C++ solution

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()) { .. }

如果仅想允许读取访问权限,则删除第二个getter(并且可能将指针更改为const bool *).如果两个都需要,则需要两个getter. (这是因为读/写不能用于读取const对象).

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).

这篇关于指向布尔值的C ++指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆