C++重载ostream和istream输出自定义对象

1. 重载

   C++的iostream库和C中的stdio库中分别的cout/cinprintf/scanf相比有哪些优势呢?

  • 首先是类型处理更加安全和智能,我们无须应对%d、%f
  • 而且扩展性极强,对于新定义的类,printf想要输入输出一个自定义的类的成员是天方夜谭的,而iostream中使用的位运算符都是可重载的
  • 并且可以将清空缓冲区的自由交给了用户,而且流风格的写法也更加自然和简洁。
#include 
#include using namespace std;class stu{
public:int age;int score;string name;stu(int age,int score,string name):age(age),score(score),name(name){}friend ostream& operator << (ostream & os, stu& s){os << s.age << ' ' << s.score << ' ' << s.name << endl;return os;}friend istream& operator >> (istream& is, stu& s){cin >> s.age >> s.score >> s.name;return is;}
};
int main(){srand(unsigned int(time(NULL)));stu s1(24, 100, "wjh");cout << s1;stu s2(1,1,"as");cin >> s2;cout << s2;system("pause");return 0;
}

2. friend友元函数

  在重载ostream重载运算符<<的时候,需要使用到friend友元函数,因为可能会访问stu对象的私有函数成员,需要访问权限。
  当不使用友元函数的时候,这个函数就是成员变量。
实例:

#include 
using namespace std;class Box
{double width;
public:friend void printWidth( Box box );void setWidth( double wid );
};// 成员函数定义
void Box::setWidth( double wid )
{width = wid;
}
void printWidth( Box box )
{/* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */cout << "Width of box : " << box.width <<endl;
}int main( )
{Box box;// 使用成员函数设置宽度box.setWidth(10.0);// 使用友元函数输出宽度printWidth( box );return 0;
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部