【发布时间】:2020-10-30 15:53:03
【问题描述】:
我试图重载运算符“
struct Log
{
std::string outString;
template<typename T>
friend Log& operator<<(Log& log, const T& t)
{
std::stringstream temp;
temp << t;
std::string str = temp.str();
log.outString += str;
if(str == "endl" || str == "\n")
{
//end of line -> pass string to custom print function
}
return log;
}
};
我在这一行遇到了分段错误:
log.outString += str;
应该这样称呼。
log << "blub: " << 123 << "endl";
【问题讨论】:
-
尝试用
if(str == "endl" || str == "\n")替换if(t == "endl" || t== "\n") -
我建议对
"endl"使用比字符串更健壮的东西,因为编译器没有机会帮助您解决拼写错误。例如一个枚举
标签: c++ string operator-overloading stringstream