首页 > 解决方案 > 错误:“const char*”和“const char*”类型的无效操作数到二进制“operator+”

问题描述

我的代码有问题。每当我尝试将两个字符串一起打印出来时,它都会显示错误。我什至尝试将引号从 "" 更改为 ' ' - 但它仍然不起作用并显示负数。怎么了?

#include <iostream>


using namespace std;

template<typename T, typename R>

auto sum(T a, R b)
{
    return a + b;
}



int main()
{


    cout << sum("hello", "world") << endl;

    return 0;
}

标签: c++

解决方案


当您通过"hello""world"它们不是时,它们是不支持串联strings的 's 数组。const char

sum如果需要对数组求和,可以使用模板特化const char

#include <iostream>
using namespace std;


template<typename T, typename R>
auto sum(T a, R b)
{
    return a + b;
}

auto sum(const char* a, const char* b)
{
    return string(a) + string(b);
}

int main()
{

    cout << sum("hello", "world") << endl;

    return 0;
}

或者修改参数以使它们成为可以与 operator 连接的字符串+

#include <iostream>
using namespace std;


template<typename T, typename R>
auto sum(T a, R b)
{
    return a + b;
}

int main()
{

    cout << sum(string("hello"), string("world")) << endl;

    return 0;
}

推荐阅读