std::字符串 '+' : 不能添加两个指针
std::string '+' : cannot add two pointers
为什么要赋值
std::string s="aaa"+1
工作正常,而
std::string s="aaa"+1+"bbb"
获取错误Error 14 error C2110: '+' : cannot add two pointers
没有+
运算符来连接 C 字符串。C 字符串只是指针 ( const char *
(,所以如果你给它添加一个数字,它只会增加该指针。之后,将其转换为C++字符串:
std::string s = "aaa" + 1
|=======|
"aa"
const char *
|==============|
"aa"
std::string
然后在第二步中,当您尝试连接第二个字符串时,它会失败,因为虽然向指针添加常量仍然有意义(即使不是在您的情况下(,但您无法理解添加两个指针。
"aaa" + 1 + "bbb"
|========|
"aa"
const char *
|===|
const char *
为了确保您实际连接并且不对指针求和,我建议使用 stringstream
.这也确保您的常量数正确转换为string
。
std::stringstream ss;
ss << "aaa" << 1 << "bbb";
std::string s = ss.str();
这将适用于operator<<
重载的每个类型。
std::string s="aaa"+1;
这只是编译,但很可能没有做你想要的:它向文字"aaa"
衰减到的const char*
加 1,然后从该指针构造std::string
,从而产生s == "aa"
。
当使用 operator+
连接字符串时,至少一个操作数必须具有类型 std::string
,另一个可以是 const char*
或可转换为该操作数。例如:
std::string s="aaa"+std::to_string(1);
或
std::string s="aaa"+std::to_string(1)+"bbb";
第一个有效,因为"abc" + 1
实际上是字符串"bc"
(更改了实际字符串以使其更容易看到(。这很简单,就像做例如
char array[] = "abc;
std::string str = &array[1];
第二个不起作用,因为您无法以这种方式附加两个字符串文本。您需要确保其中一个已经是std::string
对象。
如果你想创建字符串"aaa1"
那么我建议你看看函数std::to_string
。
这是此上下文中的附加信息。一般穷人的解决方案是让它工作一半:
void JTube::checkNode(ITCXMLNode current_node, char * tagName){
if(!current_node.d) {
string s = "XML tag missing:";
s = s + tagName;
exitreason(s);
}
}
相关文章:
- 一个对象的两个指针.删除了一个指针,对象仍然存在
- 如何将值添加到嵌套结构中,该结构在C++中有两个指针
- 比较两个指针时">="运算符的奇怪行为
- 根据下面的作者,如果两个指针指向不同的数组,则比较的第一个版本将未定义
- 为什么 fdump-class-hierarchy 为虚函数提供了两个指针 int vtable
- 错误 :"+" 无法添加两个指针
- 使与同一数组无关的两个指针减去未定义行为的基本原理是什么?
- 为什么当我在同一内存中各有两个指针时,我必须调用"delete"两次?
- 如何加入两个指针以将其串在一起并将其存储在数组或字符中
- 如何在多线程 c++ 17 程序中交换两个指针
- 这两个指针怎么能有相同的值
- 为什么两个指针都有相同的内存地址
- 两个指针之间的差异是合法的 c++17 常量表达式
- 为什么两个指向相同链接的两个指针在这里表现不同
- 这两个指针代码有什么区别
- 使用指针在Qt Creator UI中的其他两个指针之间切换
- 重写虚函数协变返回类型(两个指针)
- 想要一种在C++中交换两个指针的有效方法
- 在delete()之后不会断言两个指针都指向NULL
- 更改指针指向指针的位置,同时保持其他两个指针的值