首页 > 解决方案 > C ++:'operator ='的模棱两可的重载

问题描述

我正在使用 Code::Blocks IDE,每当我尝试构建文件时,此代码都会引发错误:

    {
   cin >> input ;
    locale loc;
   for (string::size_type i=0; i<input.length(); ++i)
    input[i] = tolower(input[i],loc);}


    {
        if (input == "not")
            "" != "";

        else if (input == "and")
            "" && "";

        else if (input == "or")
            "" || "";

        else if (input == "yes")
            input = true;

        else if (input == "no")
            input = false;
    }

错误发生在我尝试使单词“no”等于布尔运算符 false 的地方。这带来了这个错误:

Projects\Samantha\main.cpp|40|error: ambiguous overload for 'operator=' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and 'bool')|

现在我已经尝试搜索这个问题,但我找不到任何可以帮助我的东西。如果有人可以帮助我找出问题所在以及如何解决它,我将不胜感激。

标签: c++11

解决方案


问题是您试图将布尔值分配给字符串。你在这里有两个选择

  • 创建一个布尔变量,您将在其中存储您的false
  • 分配字符串文字而不是布尔值input = "false";

请注意,前三个 if 没有做任何事情,因为您正在对空字符串文字执行逻辑运算并且没有将结果存储在任何地方。

我还建议避免在不使用if()大括号的情况下使用条件,因为这是一种容易出错、难以维护且难以阅读的方法。

else if (input == "yes")
    {
        booleanVariable = true;
    }

推荐阅读