1

出于某种原因,由于我的 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)

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

4

2 回答 2

3

你不能调用std::string::operator+int 类型,使用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) + "}";
于 2013-01-31T04:24:06.727 回答
0

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

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

例子

于 2013-01-31T04:30:40.307 回答