输入输出运算符重载

混江龙づ霸主 提交于 2019-11-26 20:22:35

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!