c++ - 字符串连接,错误

标签 c++ string concatenation

Container.cc: In member function ‘std::string Container::tostring()’: Container.cc:125:27: error: invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’ cadena= "("+ this->id+ ","+this->weight +","+ this->price+")";

我怎么能解决这个错误,是c++

这是代码:

string Container::tostring()
    {
        cadena= "("+ this->id+ ","+this->weight +","+ this->price+")";

        return cadena;
    }

最佳答案

你至少应该这样写

string Container::tostring()
    {
        cadena= "("+ std::to_string( this->id ) + "," + std::to_string( this->weight ) + "," +  std::to_string( this->price ) + ")";

        return cadena;
    }

另一种方式如下

#include <sstream>

//...

string Container::tostring()
    {
        std::ostringstream os;

        os << "(" << this->id << "," << this->weight << "," << this->price << ")";
        cadena = os.str();

        return cadena;
    }

关于c++ - 字符串连接,错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30571880/

相关文章:

c++ - OpenGL 顶点缓冲区渲染不正确

c++ - 包括带有 libiota 的 header

php - 使用PHP计算字符串中的五个逗号后,将字符串转换为数组

c++ - 字符串验证函数出错

matlab - 注释某些行时 Matlab 中的单元格数组串联错误

字符串变量未在多行字符串中替换

c++ - 如何在 C++ 中访问父作用域的变量?

c++ - 如何防止在 MayBeGesture 状态下超时删除手势?

c++ - 从字符串读入字符串流

wpf - 通过 XAML 连接字符串