【问题标题】:Error Message: "no match for 'operator+='" after using "string* +="错误消息:使用“string* +=”后“不匹配 'operator+='”
【发布时间】:2020-10-08 05:21:19
【问题描述】:

我对 C++ 有疑问。我使用了一个字符串指针并想动态添加另一个字符串。 但是后来我收到了这个错误消息:

'operator+=' 不匹配(操作数类型为 'std::__cxx11::string* {aka std::__cxx11::basic_string*}' 和 'std::__cxx11::string {aka std::__cxx11 ::basic_string}')

void Stammbaum::printTree(Node* node, string* s){
    printLeftTree(node, s, 0);
}

void Stammbaum::printLeftTree(Node* node, string* s, int i){
    if(node == NULL)
        return;

    if(i != 0)
        printLeftTree(node->Mutter, s, 1);

    string temporaryString;
    temporaryString = "/-- " + node->vorname + " " + node->nachname + "\n";
    s += temporaryString;                     <------------------------------Getting the error in this Line--

    printLeftTree(node->Vater, s, 1);
}

【问题讨论】:

    标签: c++ string pointers


    【解决方案1】:

    s 是一个字符串指针,所以应该是这个

    *s += temporaryString;
    

    如果我理解你在这里尝试做什么,那么通常在 C++ 中你会使用引用而不是指针,那么你就不需要*

    【讨论】:

      【解决方案2】:

      变量s 是一个指向std::string 对象的指针,尝试添加到它会添加到指针本身而不是它指向的对象。

      你需要取消引用指针来获取std::string对象:

      *s += temporaryString;
      

      更好的解决方案 (IMO) 是使用 references 而不是指针。

      【讨论】:

        【解决方案3】:

        也可以使用std::string成员函数append,在末尾追加字符串;

        s->append( temporaryString );
        

        像其他人建议的那样,使用引用而不是指针

        【讨论】:

          猜你喜欢
          • 2012-08-04
          • 2011-10-06
          • 2011-12-10
          • 2013-07-31
          • 1970-01-01
          • 1970-01-01
          • 2018-01-04
          • 1970-01-01
          • 2011-12-08
          相关资源
          最近更新 更多