c++ - 错误:“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;
}
解决方案
当您通过"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;
}
推荐阅读
- corda - Corda 状态持续存在于 DB 中的确切位置(IOU 示例)
- javascript - 在 iFrame 中定位元素时遇到问题
- mongodb - Mongodb中非常慢的日期范围查询
- vba - 告诉 VBA 查看 64 位注册表视图
- reactjs - 如何在 ReactJS 中的按钮上添加多个 onClick 函数
- javascript - iPhone Chrome 上的 navigator.sendBeacon() 未发布到安全网站
- python - python-shell历史
- apache - 防止 htaccess 将 ¤ 更改为符号
- msbuild - MSBuild Force Item Include 被视为自定义/文字
- python-2.7 - Python2.7:我可以为 ODE 求解器中雅可比行列式的前向差分近似设置步长吗?