zoukankan      html  css  js  c++  java
  • c++重载>>和<<

    在重载输出输入运算符的时候,只能采用全局函数的方式(因为我们不能在ostream和istream类中编写成员函数),这里才是友元函数真正的应用场景。对于输出运算符,主要负责打印对象的内容而非控制格式,输出运算符不应该打印换行符;对于输入运算符,必须处理可能失败的情况(通常处理输入失败为默认构造函数的形式),而输出运算符不需要。

     1 #include<iostream>
     2 using namespace std;
     3 class Test {
     4     friend ostream & operator<<(ostream &out, Test &obj);
     5     friend istream & operator >> (istream &in, Test &obj);
     6 public:
     7     Test(int a = 0, int b = 0)
     8     {
     9         this->a = a;
    10         this->b = b;
    11     }
    12     void display()
    13     {
    14         cout << "a:" << a << " b:" << b << endl;
    15     }
    16 public:
    17 
    18 
    19 private:
    20     int a;
    21     int b;
    22 };
    23 ostream & operator<<(ostream &out, Test &obj)
    24 {
    25     out << obj.a << " " << obj.b;
    26     return out;
    27 }
    28 istream & operator>>(istream &in, Test &obj)
    29 {
    30     in >> obj.a>> obj.b;
    31     if (!in)
    32     {
    33         obj = Test();
    34     }
    35     return in;
    36 }
    37 int main()
    38 {
    39     Test t1(1, 2);
    40     cout << t1 << endl;
    41     cout << "请输入两个int属性:";
    42     cin >> t1;
    43     cout << t1 << endl;;
    44     cout << "hello world!
    ";
    45     return 0;
    46 }

    输入正确时输入错误时

  • 相关阅读:
    [題解]51nod_1515_明辨是非
    任务调度问题(贪心) hdu4864
    B站学习记:贪心与博弈
    poj1505(二分+贪心)
    温故知新:互质排列
    Radar Installation(利用数据有序化进行贪心选择)
    Wooden Sticks(贪心)
    计算a除b的第一位小数 in C++.
    龙龙的暑假贪心算法大冒险
    HDU-2037(贪心)
  • 原文地址:https://www.cnblogs.com/yangguang-it/p/6489550.html
Copyright © 2011-2022 走看看