Bre*_*men 10 c++ std stringstream c++11
我想做一个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;
}
};
Run Code Online (Sandbox Code Playgroud)
它没有编译,因为我收到此错误:
error: use of deleted function ‘std::basic_stringstream<char>& std::basic_stringstream<char>::operator=(const std::basic_stringstream<char>&)’
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它不起作用.我也试过logString = move(a.logString);了.结果相同.我将非常感谢所有的帮助.
编辑:这是我的代码,我已经应用了大多数用户建议的更改,并且在我的代码中他们没有编译.我仍然在一开始就收到错误struct.
第40行: ../src/CLogger.h:40:9: error: use of deleted function ‘std::basic_stringstream<char>::basic_stringstream(const std::basic_stringstream<char>&)’
第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&)’
如果需要任何其他信息,我将提供.
Ant*_*vin 12
std::stringstream是不可复制的.要复制内容,您只需将一个流的内容写入另一个流:
logString << a.logString.str();
Run Code Online (Sandbox Code Playgroud)
更新:此外,如果您没有遵循operator=使用复制构造函数实现复制和交换习惯用语的好建议,则必须先清除流:
logString.str({});
logString << a.logString.str();
Run Code Online (Sandbox Code Playgroud)
要不就
logString.str(a.logString.str());
Run Code Online (Sandbox Code Playgroud)
您也可能想要使用rdbuf():
logString << a.logString.rdbuf();
Run Code Online (Sandbox Code Playgroud)
但是这是不正确的,因为它改变了的状态a.logString(尽管a.logString是const,a.logString.rdbuf()是一个指向非const对象).以下代码演示了这一点:
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;
Run Code Online (Sandbox Code Playgroud)
std::stringstream::operator=通过移动分配其成员和基类来获取其右侧的内容。
在您的重载中,operator=输入参数是const。logString因此,无法移动输入参数的成员。此外,operator=(std::stringstream const&)instringstream被声明为已删除。重载解析选择删除的运算符,您理所当然地会收到编译错误。
logline_t& operator =(const logline_t& a) {
logString.str(a.logString.str());;
logLevel = a.logLevel;
currentTime = a.currentTime;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4940 次 |
| 最近记录: |