c++11 - 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')|
现在我已经尝试搜索这个问题,但我找不到任何可以帮助我的东西。如果有人可以帮助我找出问题所在以及如何解决它,我将不胜感激。
解决方案
问题是您试图将布尔值分配给字符串。你在这里有两个选择
- 创建一个布尔变量,您将在其中存储您的
false
值 - 分配字符串文字而不是布尔值
input = "false";
请注意,前三个 if 没有做任何事情,因为您正在对空字符串文字执行逻辑运算并且没有将结果存储在任何地方。
我还建议避免在不使用if()
大括号的情况下使用条件,因为这是一种容易出错、难以维护且难以阅读的方法。
else if (input == "yes")
{
booleanVariable = true;
}
推荐阅读
- html - bootstrap-如何正确对齐结构?
- java - 在 java Android Studio 中找不到局部变量“OpenCVLoader”
- c# - 将数据库附加到 SQL Server
- django - Django,我如何比较剩菜
- java - 如何在我的 HashMap 而不是整个 HashMap 中找到仅某些整体的最高值?
- r - 将带有时区对象的日期时间传递给闪亮仪表板中的日期范围输入
- mysql - 选择最近一天 IGNORING 时间戳的所有记录的正确 SQL 语句是什么?
- c# - 如何对大序列进行多线程处理
- javascript - 用javascript写一个图片滑动游戏
- vb.net - 如何在 Start.Process 中运行长字符串