我们使用printf 的时候或者自己构造的printf,有的时候会有这样的烦恼,输出很容易出错,如果 int 类型对应 %s 那么必然要崩溃。为了解决问题结果打log崩溃,是令人很恼火的事。
c++ 的输出或者日志输出
std::cout << “hello” << endl;
c++ 98 实现了如下函数:
arithmetic types (1)
ostream& operator<< (bool val);
ostream& operator<< (short val);
ostream& operator<< (unsigned short val);
ostream& operator<< (int val);
ostream& operator<< (unsigned int val);
ostream& operator<< (long val);
ostream& operator<< (unsigned long val);
ostream& operator<< (float val);
ostream& operator<< (double val);
ostream& operator<< (long double val);
ostream& operator<< (void* val);
如果我们要使用 << 输出自己的结构体,那么只需要自己实现 << 操作符即可
std::ostream& operator << (std::ostream& os,std::list<std::string>& lst)
{
int i = 0;
for (std::string& var : lst)
{
os << "item: " << i++ << " " << var << ",";
}
return os;
}
输出一个链表的内容
std::list<std::string> lst;
lst.push_back("gaga");
lst.push_back("lala");
cout << lst << endl;
自动会少一些bug,烦恼会减少不少.