C ++或字符串比较保持抛出Bool错误

时间:2015-07-03 20:49:02

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

我一直在与我认为可能是一个简单的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’

2 个答案:

答案 0 :(得分:4)

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

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

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

(啊,单个=可以产生什么不同......)

答案 1 :(得分:2)

错误消息非常清楚,您在上次检查中拼错了==

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

由于inRarity="common"的类型为string而你正在尝试或者它是一个布尔表达式,它告诉你那里没有匹配的{{1}运营商。