std::字符串 '+' : 不能添加两个指针

std::string '+' : cannot add two pointers

本文关键字:两个 指针 不能 字符串 std 添加      更新时间:2023-10-16

为什么要赋值

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);   
     }
   }