其他分享
首页 > 其他分享> > 输入输出运算符重载

输入输出运算符重载

作者:互联网

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

标签:feet,inches,Distance,int,输入输出,C++,运算符,重载
来源: https://www.cnblogs.com/wanghao-boke/p/11325192.html