You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++编译报错:从bool右值初始化std::string&非const引用求解

问题根因
  • 错误的多条件写法:你写的"1"||"3"||"5"||"7"||"9"在C++中不会产生“匹配任一字符串”的效果,逻辑或运算符||对字符串字面量(本质是const char*类型)运算时,只要前一个指针非空就会直接返回布尔值true,所以你实际传给hasEnding函数的第二个参数是bool类型的值,和函数要求的std::string&类型完全不匹配,这就是编译报错的直接原因。
  • hasEnding函数参数设计不合理:你不需要修改传入的两个字符串,应该将参数声明为const std::string&,否则也无法传入临时构造的字符串对象,额外限制入参合法性。
  • 代码还缺失了输入输出所需的头文件<iostream>,就算修复类型问题也会因为找不到cout、cin的定义报错。
修复方案

最优方案:直接用取模运算判断奇偶

判断整数奇偶完全不需要转字符串做后缀匹配,直接对2取模即可,性能更高代码也更简洁,修改后的完整代码如下:

#include <iostream>
#include <string>
#include <math.h>
using namespace std;

int main() {
    int current_num;
    cout << "Type a positive number: "; // 输入数字后按回车
    cin >> current_num;
    while (current_num >= 2) {
        cout << current_num << endl;
        if (current_num % 2 == 1) { // 奇数判断
            current_num = current_num * 3 + 1;
        } else { // 偶数判断
            current_num = current_num / 2;
        }
    }
    return 0;
}

保留后缀判断逻辑的修改方案(仅用于学习验证)

如果需要保留你原本的后缀判断写法,按以下步骤修改:

  1. 修改hasEnding函数的参数为const引用:
bool hasEnding (const std::string &fullString, const std::string &ending) {
    if (fullString.length() >= ending.length()) {
        return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
    } else {
        return false;
    }
}
  1. 把错误的多条件或写法改成逐个调用hasEnding判断:
odd = hasEnding(s, "1") || hasEnding(s, "3") || hasEnding(s, "5") || hasEnding(s, "7") || hasEnding(s, "9");
even = hasEnding(s, "0") || hasEnding(s, "2") || hasEnding(s, "4") || hasEnding(s, "6") || hasEnding(s, "8");
  1. 补上头文件#include <iostream>。

内容的提问来源于stack exchange,提问作者greenCode_TM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:12:00