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

1. 重载

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

  • 首先是类型处理更加安全和智能,我们无须应对%d、%f
  • 而且扩展性极强,对于新定义的类,printf想要输入输出一个自定义的类的成员是天方夜谭的,而iostream中使用的位运算符都是可重载的
  • 并且可以将清空缓冲区的自由交给了用户,而且流风格的写法也更加自然和简洁。
#include <iostream>
#include <string>

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 <iostream>
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值