当前位置: 动力学知识库 > 问答 > 编程问答 >

C++ - OR String Comparison Keeps Throwing a Bool Error

问题描述:

I have been fighting with what I think is probably a simple C++ problem for hours now and I could really use some help. Here is what I would like to do:

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;

}

But I keep getting errors when I try to compile (using g++ in Ubuntu):

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’

网友答案:

In your original fragment, the problem I see is that you should change

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

to

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

(Ah, what a difference a single = can make...)

网友答案:

The error message is pretty clear, you misspelled == in the last check:

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

And since inRarity="common" has the type string and you're trying to or it to a boolean expression, it's telling you there's no matching || operator.

分享给朋友:
您可能感兴趣的文章:
随机阅读: