C++自定义插入操作符和提取操作符

来源:互联网 发布:淘宝上回收手机可靠吗 编辑:程序博客网 时间:2024/06/08 09:39
#include <iostream>#include <cstring>/* run this program using the console pauser or add your own getch, system("pause") or input loop */class data{private:char hh[200];public:int i;float t;char ch;data(int a,float b,char c){i = a;t = b;ch = c;strcpy(hh,"哼!要不是友元函数,作为私有元素的我才不会被你看光光!"); }friend std::ostream &operator<<(std::ostream &,data);//将插入操作符函数定义为类的友元函数访问类的私有元素hh }; std::ostream &operator<<(std::ostream &out,data d){//重载插入操作符 out << d.i << " , ";out << d.t << " , ";out << d.ch << " , ";out << d.hh << std::endl; return out;}std::istream &operator>>(std::istream &in,data &d){//重载提取操作符 std::cout << "给 i, f ,ch 赋值:"; in >> d.i;in >> d.t;in >> d.ch;return in; } int main(int argc, char** argv) {class data d(12,4.5,'g');std::cout << d; std::cin >> d;std::cout << d; return 0;}