在将<<操作符作为朋友函数重载时,我真的很困惑。
This line works fine
cout << endl;
But this line gives compilation issue. Why ??
operator <<(cout, endl);以下是示例代码
class Logger
{
int _id;
string _name;
public:
Logger(int id, string name):_id(id),_name(name){
cout<<"Constructor"<<endl;
}
~Logger(){
cout<<"destructor"<<endl;
}
friend ostream& operator <<( ostream& out,Logger& log);
};
ostream& operator << (ostream& out,Logger& log)
{
out<<log._id<<" "<<log._name;
return out;
}那么return语句的需求是什么呢?在没有返回的情况下,下面的语句也可以正常工作。
cout<<日志<< endl << endl << log2 << endl << log3 << endl;
发布于 2020-06-08 02:44:56
接受流操纵器的operator<<是basic_ostream的成员函数。您不能像调用自由函数一样调用它;您必须将其作为成员函数调用:
std::cout.operator<<(std::endl)另一方面,接受std::string的流插入器是一个自由函数,您可以使用通常的函数调用来调用它:
std::string text = "Hello, world";
operator<<(std::cout, text);但不是作为成员函数。
使用std::endl通常是错误的;'\n'结束一行,而不使用std::endl所做的额外内容。
https://stackoverflow.com/questions/62248036
复制相似问题