gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:57:27 25 4
gpt4 key购买 nike

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

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

最佳答案

你不能在 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) + "}";

关于c++ - 添加字符串时遇到问题... (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14618428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com