简体   繁体   English

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

[英]Having trouble with adding strings… (c++)

For some reason my source file will not compile because of my toString function. 出于某种原因,由于我的toString函数,我的源文件将无法编译。 It claims it cannot recognize the + symbol to append strings. 它声称无法识别附加字符串的+符号。 Here's my code: 这是我的代码:

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

symbol, qty, and price are variables in the class symbol,qty和price是类中的变量

I get the following message from the compiler... 我从编译器得到以下消息......

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)

Anyone know what's going on here? 谁知道这里发生了什么?

You can't call std::string::operator+ on int types, use std::stringstream 你不能在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();

Or use std::to_string if you use C++11 and boost::lexical_cast to cast integer types to string first: 或者如果使用C ++ 11和boost :: lexical_cast将整数类型转换为字符串,则使用std :: to_string

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

If qty and price are ints or something similar you can do the following (in C++11): 如果qtyprice是整数或类似的东西,你可以执行以下操作(在C ++ 11中):

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

example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM