C++能够使用流提取运算符>>和流插入运算符<< 来输入输出内置数据类型,也可以重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型。
我们有时需要把运算符重载函数声明为类的友元函数,这样我们就能不用构造对象而直接调用函数。
/*** inputOver.cpp ***/ #include<iostream> using namespace std; class Distance { private: int feet; int inches; public: Distance() { feet = 0; inches = 0; } Distance(int f,int i) { feet = f; inches = i; } friend ostream &operator<<(ostream &output,const Distance &D) { output << "F: " << D.feet << " I: " << D.inches; return output; } friend istream &operator>>(istream &input,Distance &D) { input >> D.feet >> D.inches ; return input; } }; int main() { Distance D1(11,10),D2(5,11),D3; cout << "Enter the value of object : " << endl; cin >> D3; cout << "First Distance : " << D1 << endl; cout << "Second Distance : " << D2 << endl; cout << "Third Distance : " << D3 << endl; return 0; }
运行结果:
exbot@ubuntu:~/wangqinghe/C++/20190808$ g++ inputOver.cpp -o inputOver
exbot@ubuntu:~/wangqinghe/C++/20190808$ ./inputOver
Enter the value of object :
70 10
First Distance : F: 11 I: 10
Second Distance : F: 5 I: 11
Third Distance : F: 70 I: 10
如果将重载程序写成成员函数形式,会是以d1 << cout的形式输出数据。
/*** memberOver.cpp ***/ #include<iostream> using namespace std; class Distance { private: int feet; int inches; public: Distance() { feet = 0; inches = 0; } Distance(int f,int i) { feet = f; inches = i; } ostream &operator<<(ostream &os) { os << "F: " << feet << " I: " << inches << endl; return os; } }; int main() { Distance d1(20,18); d1 << cout; return 0; }
运行结果:
exbot@ubuntu:~/wangqinghe/C++/20190808$ g++ memberOver.cpp -o memberOver
exbot@ubuntu:~/wangqinghe/C++/20190808$ ./memberOver
F: 20 I: 18