gpt4 book ai didi

c++ - 不能将 operator= 与 std::stringstream 一起使用

转载 作者:可可西里 更新时间:2023-11-01 15:40:02 24 4
gpt4 key购买 nike

我正在尝试制作 struct ,其中一名成员属于 std::stringstream类型。我正在使用 C++11,并根据 http://www.cplusplus.com/reference/sstream/stringstream/operator=/我能行。

这是我的代码:

struct logline_t
{
stringstream logString; /*!< String line to be saved to a file (and printed to cout). */
ElogLevel logLevel; /*!< The \ref ElogLevel of this line. */
timeval currentTime; /*!< time stamp of current log line */

logline_t& operator =(const logline_t& a)
{
logString = a.logString;
logLevel = a.logLevel;
currentTime = a.currentTime;

return *this;
}
};

它没有编译,因为我收到这个错误:

error: use of deleted function ‘std::basic_stringstream<char>& std::basic_stringstream<char>::operator=(const std::basic_stringstream<char>&)’

我不明白为什么它不起作用。我试过logString = move(a.logString);以及。同样的结果。我将不胜感激。

编辑:这是我的代码,我已经应用了大多数用户建议的更改,但在我的代码中他们没有编译。我在 struct 的最开始仍然遇到错误.

CLogger.h

第 40 行:../src/CLogger.h:40:9: error: use of deleted function ‘std::basic_stringstream<char>::basic_stringstream(const std::basic_stringstream<char>&)’

CLogger.cpp

第 86 行:../src/CLogger.cpp:86:41: error: use of deleted function ‘CLogger::logline_t::logline_t(const CLogger::logline_t&)’

第 91 行:../src/CLogger.cpp:91:9: error: use of deleted function ‘CLogger::logline_t::logline_t(const CLogger::logline_t&)’

如果需要任何其他信息,我会提供。

最佳答案

std::stringstream 不可复制。要复制内容,您只需将一个流的内容写入另一个流即可:

logString << a.logString.str();

更新:此外,如果您不遵循使用复制构造函数的 copy-and-swap 习语实现 operator= 的好建议,则必须先清除流:

logString.str({});
logString << a.logString.str();

或者只是

logString.str(a.logString.str());

您可能还想改用 rdbuf():

logString << a.logString.rdbuf();

但这是不正确的,因为它改变了 a.logString 的状态(尽管 a.logStringconst a.logString.rdbuf() 是指向非常量对象的指针)。以下代码对此进行了演示:

logline_t l1;
l1.logString << "hello";
logline_t l2, l3;
l2 = l1;
l1.logString << "world";
l3 = l1;
// incorrectly outputs: l2: hello, l3: world
// correct output is: l2: hello, l3: helloworld
std::cout << "l2: " << l2.logString.str() << ", l3: " << l3.logString.str() << std::endl;

关于c++ - 不能将 operator= 与 std::stringstream 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31157733/

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