【问题标题】:Bool = true when it should = false in C++Bool = true 当它应该在 C++ 中 = false
【发布时间】:2014-01-11 01:41:33
【问题描述】:

这可能是我的另一个新手错误,但我似乎找不到可以回答它的问题,我想如果我公开的无能在私下帮助他人,那可能是最好的。无论如何,自责结束,到手头的问题上。

在我的文字冒险的标题中,我有一个这样的结构:

struct roomStruct
{
    // The room the player is currently in, and its interactive objects.
    string roomName;
    string size;
    bool exits[dirnum];
    bool rustyKeyIn;
    bool goldKeyIn;
        ...

还有一个像这样的实例:

void genRooms(roomStruct *rms)
{
    // Generating the rooms of the house, and what items they contain
    rms[entrance].roomName.assign("the entrance hallway. It's a small room with an exit to the south.");
    rms[entrance].exits[north] = noexit;
    rms[entrance].exits[east] = noexit;
    rms[entrance].exits[south] = livingroom;
    rms[entrance].exits[west] = noexit;
    rms[entrance].rustyKeyIn = false;
    rms[entrance].goldKeyIn = false;

在 int main() 里面我有一个这样的函数:

// Generate the world.
    roomStruct rooms[roomnum];
    genRooms(rooms);

此外,我有我认为的问题区域:

// Check for items in the current room.
    if( rooms[currentRoom].rustyKeyIn = true )
    {
        cout << "A rusty key." << endl;
    }
    if( rooms[currentRoom].goldKeyIn = true )
    {
        cout << "A gold key." << endl;
    }
        ...

现在的问题。没有编译器问题,但是当我运行代码时,每个房间都列出了每个项目,无论 bool 设置为 true 还是 false。毫无疑问,解决方案很简单,但它坚持让我望而却步。

【问题讨论】:

  • 您使用的是= 而不是==。编译器通常会就此发出警告。
  • 你应该使用构造函数而不是genRooms
  • @Phillip Kinkade 矿没有。

标签: c++ boolean


【解决方案1】:

你错误地使用了assign操作符,它总是将rustyKeyIn设置为true并返回true。 所以你应该使用比较运算符 operator ==

if( rooms[currentRoom].rustyKeyIn = true )

应该是

if( rooms[currentRoom].rustyKeyIn == true )
//                                ^^^

或者干脆做

if (rooms[currentRoom].rustyKeyIn)

【讨论】:

  • 或者,更好的是if (rooms[currentRoom].rustyKeyIn) { ... }
  • 我是个白痴。就连我也应该注意到那个。谢谢XD
  • 别担心,几乎每个人都至少成功过一次。特别是如果您在 C 和其他使用 = 作为测试而不是赋值的语言之间移动(这里考虑 VHDL)。
【解决方案2】:

您使用的是= 而不是==

当你这样做时:

if(a = true) {
    ...
}

If 将 a 设置为 true,然后询问表达式的结果(a 的新值)是否为 true,现在为 true。

你想要的是:

if(a == true) {
    ...
}

或者不那么冗长(并且更常见):

if(a) {
    ...
}

【讨论】:

    【解决方案3】:

    使用== 表示相等,使用= 表示赋值。

    【讨论】:

      猜你喜欢
      • 2014-01-11
      • 2017-02-21
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      • 2013-06-27
      • 1970-01-01
      相关资源
      最近更新 更多