鱼C论坛

 找回密码
 立即注册
查看: 280|回复: 1

为什么改为auto会报错得这样写才对

[复制链接]
发表于 2024-2-26 21:02:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <bits/stdc++.h>
using namespace std;

int main() {
    string instr, poststr;
    cin >> instr >> poststr;
    
    auto build = [&](string instr, string poststr) { //为什么改为auto会报错得这样写才对function<void(string,string)>build=[&](string instr,string poststr)
        if(instr.size() <= 0) return;
        
        cout << poststr.back();
        int mid = instr.find(poststr.back());
        
        build(instr.substr(0, mid), poststr.substr(0, mid));
        build(instr.substr(mid + 1), poststr.substr(mid, poststr.size() - instr.size() + mid));
    };
    
    build(instr, poststr);
    
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-2-26 21:03:08 | 显示全部楼层
在C++中,使用`auto`关键字来自动推导变量的类型是一种方便的特性。但是,在你的代码中,不能直接使用`auto`来定义一个函数。

在这种情况下,你需要显式指定函数的返回类型。这可以通过在函数定义前面添加返回类型来实现,如下所示:
string build(string instr, string poststr) {
    // 函数体
}

这样,编译器就能正确地推导出函数的返回类型,并且你可以在函数体内进行处理并返回该类型的值。

另外,你还需要注意函数参数的传递方式。在你的代码中,函数的参数名与`main`函数中的同名变量产生了冲突。为了避免这种冲突,你可以选择更改其中一个变量的名称,或者使用不同的作用域来解决该问题。这里我为你提供了一种修改的方法:
#include <iostream>
using namespace std;

string build(string instr, string poststr) {
    // 函数体
}

int main() {
    string instr, poststr;
    cin >> instr >> poststr;

    string result = build(instr, poststr);
    cout << result << endl;

    return 0;
}

在这个修改后的代码中,函数`build`接受两个`string`类型的参数,并返回一个`string`类型的结果。在`main`函数中,我们调用`build`函数,将输入的字符串作为参数,并将返回的结果存储在`result`变量中,最后输出该结果。

希望能帮到你!如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-20 09:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表