重载操作符有两个参数,左边的参数是steam类的参数,右边是要进行操作的类的对象,在这里用string类举一个例子
#include <iostream>
#include <string>
using namespace std;
ostream & operator << (ostream &out, string &line) {
int index = line.find(' ');
int index_t = line.find('\0');
out << line.substr(0, index) << endl;
line = line.substr(index + 1, line.size());
if (index == index_t)
return out;
while (1) {
index = line.find(' ');
index_t = line.find('\0');
if (index == index_t) {
out << line;
break;
}
else {
out << line.substr(0, index) << endl;
line = line.substr(index + 1, line.size());
}
}
return out;
}
int main()
{
string line = "I love China!";
cout << line;
return 0;
}
PS:在重载的过程中,被重载操作符右边只能出现右边类的对象,否则报错(之前我就是一直在调试这个问题),当然endl还是可以使用的。