由于某些原因,我的源文件因为我的toString函数而无法编译。它声称无法识别附加字符串的+符号。这是我的代码:
string s = "{symbol = " + symbol + ", qty = " + qty + ", price = " + price + "}";
symbol,qty和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)
任何人都知道这里发生了什么?
答案 0 :(得分:3)
您无法在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();
如果您使用C ++ 11并使用boost :: lexical_cast将整数类型转换为字符串,则使用std::to_string:
std::string s = "{symbol = " + symbol + ", qty = " + std::to_string(qty)
+ ", price = " + std::to_string(price) + "}";
答案 1 :(得分:0)
如果qty
和price
是整数或类似内容,您可以执行以下操作(在C ++ 11中):
string s = "{symbol = " + symbol + ", qty = " + std::to_string(qty) + ", price = " + std::to_string(price) + "}";