如何解决在一行c ++
我试图重载运算符“
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(t == "endl" || t== "\n")
中的整数,将其替换为if(str == "endl" || str == "\n")
。
这是完整的代码:
#include <iostream>
#include <string>
#include <sstream>
struct Logg
{
std::string outString;
template<typename T>
friend Logg& operator<<(Logg& logg,const T& t)
{
std::stringstream temp;
temp << t;
std::string str = temp.str();
logg.outString += str;
if(str == "endl" || str == "\n")
{
//end of line -> pass string to custom print function
}
return logg;
}
};
int main()
{
struct Logg logg;
logg << "blub: " << 123 << "endl";
std::cout << logg.outString << std::endl;
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。