operator << 重载 注意事项

进行类的运算操作符重载时,需要把涉及到的运算符重载的类的头文件包含近年来,例如:

#include<string>

如果没有包含上面头文件,则下面的类进行operator <<重载时会出现编译错误:binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

class A{

 friend ostream& operator <<(ostream& out, A&  a);

 private:

 string str;

}

std::ostream& operator <<(std::ostream& out, A& a)
{
 out <<a.str<<endl;

}

这是因为在<string>中定义了string的"<<"重载运算符,但是没有包含头文件,所以在A中的str输出是编译器无法解析的。

原文地址:https://www.cnblogs.com/dyllove98/p/3125079.html