添加字符串时遇到问题.(C++)

Having trouble with adding strings... (c++)

本文关键字:C++ 问题 遇到 字符串 添加      更新时间:2023-10-16

由于某种原因,由于我的toString函数,我的源文件将无法编译。它声称它无法识别 + 符号来附加字符串。这是我的代码:

string s = "{symbol = " + symbol + ", qty = " + qty + ", price = " + price + "}";

交易品种、数量和价格是类中的变量

我从编译器收到以下消息...

CLEAN SUCCESSFUL (total time: 55ms)
mkdir -p build/Debug/GNU-MacOSX
rm -f build/Debug/GNU-MacOSX/Stock.o.d
g++    -c -g -MMD -MP -MF build/Debug/GNU-MacOSX/Stock.o.d -o build/Debug/GNU-MacOSX/Stock.o Stock.cpp
Stock.cpp: In member function 'std::string Stock::toString()':
Stock.cpp:56: error: no match for 'operator+' in 'std::operator+(const std::basic_string<_CharT, _Traits, _Alloc>&, const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((const char*)", qty = ")) + ((Stock*)this)->Stock::qty'
make: *** [build/Debug/GNU-MacOSX/Stock.o] Error 1

BUILD FAILED (exit value 2, total time: 261ms)

有人知道这里发生了什么吗?

不能在 int 类型上调用 std::string::operator+,请使用 std::stringstream

#include <sstream>
#include <string>
std::stringstream ss;
ss << "{symbol = " << symbol << ", qty = " << qty << ", price = " << price << "}";
std::string s = ss.str();

或者使用 std::to_string 如果使用 C++11 和 boost::lexical_cast 将整数类型首先强制转换为字符串:

std::string s = "{symbol = " + symbol + ", qty = " + std::to_string(qty) 
                + ", price = " + std::to_string(price) + "}";

如果qtyprice是整数或类似的东西,你可以执行以下操作(在C++11中):

string s = "{symbol = " + symbol + ", qty = " + std::to_string(qty) + ", price = " + std::to_string(price) + "}";