【问题标题】:how adding string and numbers in cpp works using + operator?如何使用 + 运算符在 cpp 中添加字符串和数字?
【发布时间】:2021-08-02 13:58:39
【问题描述】:

我使用 cpp 已经有一段时间了,我知道我们不能添加字符串和数字(​​因为 + 运算符没有为此重载)。但是,我看到了这样的代码。

#include <iostream>
using namespace std;
int main() {
    string a = "";
    a += 97;
    cout << a;
}

这个输出'a',我也试过这个。

string a ="";
a=a+97;

第二个代码给出了编译错误(作为 + 运算符的无效参数,std::string 和 int)。 我不想连接字符串和数字。 有什么不同?为什么一个有效,另一个无效?

我原以为a+=97 与a=a+97 相同,但它似乎有所不同。

【问题讨论】:

  • 第一个string显然不是std::string。您没有提供足够的信息,所以只能猜测。我怀疑它是某个指针类型的typedef(例如const char *),所以a += 97 进行指针运算。它也可能是一个与typedef 具有相似效果(但有其他陷阱)的宏。
  • @Peter:“第一个字符串显然不是 std::string”——嗯?你是怎么得出这个结论的?
  • @Peter 可以是 std::string : godbolt.org/z/TnbsjcfE6
  • “我不想连接字符串和数字”你想要什么?

标签: c++ stdstring


【解决方案1】:

第一个 sn-p 有效,因为 std::string overrides operator+= 将字符附加到字符串。 97是'a'的ASCII码,所以结果是"a"。

第二个 sn-p 不起作用,因为没有定义接受 std::string 和 int 的 + 运算符,并且没有从 int 或 @ 生成 std::string 的转换构造函数987654333@。 There two overloads of the + operator that take a char,但编译器无法判断使用哪一个。匹配不明确,所以报错。

【讨论】:

  • 不应该重载operator+中的3个char作为第二个参数吗?但我想它不起作用,因为97 是int 而不是char?
  • @churill:啊,是的,你是对的。但是编译器不能选择它,因为它不是一个明确的匹配。我会更新的。
  • a = a + char(97); 将是一种解决方法。
  • 嗯,但std::string::operator+=() 也为char* 过载。那么为什么没有歧义呢?我不确定我是否完全正确。
  • @FredLarson int 到 char* 不会隐式发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 2013-09-16
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
相关资源
最近更新 更多