【问题标题】:C++ OR String Comparison Keeps Throwing a Bool ErrorC++ OR 字符串比较不断抛出 Bool 错误
【发布时间】:2015-09-21 17:21:03
【问题描述】:

几个小时以来,我一直在与我认为可能是一个简单的 C++ 问题作斗争,我真的需要一些帮助。这是我想做的:

void setRarity(std::string inRarity)
{

    if ( inRarity == "c" || inRarity == "C" || inRarity == "Common" || inRarity = "common" )
    {
        rarity = "common";
    }
    //additional else-if statements following the same type of syntax as above

  return;
}

但是当我尝试编译(在 Ubuntu 中使用 g++)时,我不断收到错误:

In file included from main.cpp:6:0:
class_Card.cpp: In member function ‘void Card::setRarity(std::string)’:
class_Card.cpp:210:68: error: no match for ‘operator||’ (operand types are ‘bool’ and ‘std::string {aka std::basic_string<char>}’)
    if ( inRarity == "c" || inRarity == "C" || inRarity == "Common" || inRarity = "common" )
                                                                    ^
class_Card.cpp:210:68: note: candidate is:
class_Card.cpp:210:68: note: operator||(bool, bool) <built-in>
class_Card.cpp:210:68: note:   no known conversion for argument 2 from ‘std::string {aka std::basic_string<char>}’ to ‘bool’

【问题讨论】:

  • @Biffen:就是这样!盯着屏幕几个小时,我没有注意到我错过了一个等号!谢谢!
  • 嗯,第二个 sn-p 有 == 和括号,为什么不是答案 Biffen,让人们无法尝试回答
  • 您的第二个示例不会导致错误...

标签: c++ string boolean operator-keyword logical-operators


【解决方案1】:

在您的原始片段中,我看到的问题是您应该更改

if ( inRarity == "c" || inRarity == "C" || inRarity == "Common" || inRarity = "common" )

if ( inRarity == "c" || inRarity == "C" || inRarity == "Common" || inRarity == "common" )

(啊,一个= 能带来多大的不同...)

【讨论】:

  • 就是史蒂夫!那个单一的角色让我沉没 - 很好看!
  • @XSSerra 为什么第二个例子有错误?
  • @GlennTeitelbaum,第二个例子不会导致错误
  • @asimes 他说,“这是一个返回相同错误类型的示例片段:”
  • 那么,他应该修复它
【解决方案2】:

错误信息很清楚,您在上次检查中拼错了==

    if ( inRarity == "c" || inRarity == "C" || inRarity == "Common" || inRarity = "common" )
    {
        rarity = "common";
    }

由于inRarity="common" 的类型为string,并且您尝试将其转换为布尔表达式,因此它告诉您没有匹配的|| 运算符。

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2014-11-28
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多