c++過載string類的左移操作符
阿新 • • 發佈:2018-11-12
過載操作符有兩個引數,左邊的引數是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還是可以使用的。