首页 > 代码库 > C++运算符重载——输入/输出运算符

C++运算符重载——输入/输出运算符

为了与IO标准库一致,重载输入输出运算符函数的第一个行参应该是流的引用,第二个行参是对象的引用。

如果重载为类的成员函数,第一个行参应该是对象的引用,第二个行参是流的引用。

使用方式是 ClassObj << cout 这样与标准IO库就不一致了,所以输入输出运算符不能重载为类的成员函数,可以重载为类的友元函数和普通函数。

通常重载输出运算符的第二个行参是const的,因为输出一个类不许要更改它;

但是重载输入运算符的第二个行参必须是非const的,否则无法赋值。

重载的基本方法如下:

//重载输出运算符
ostream& operator<<(ostream& out, const ClassType& obj)
{
    out << /*想要输出的内容1*/ << /*想要输出的内容2*/ <<...;
    return out;
}

//重载输入运算符
istream& operator<<(istream& in, ClassType& obj)
{
    in >> /*想要输入的内容1*/ >> /*想要输入的内容2*/ >>...;
//检查错误 和 文件结束的可能性
return in; } 

例子:类Persion使用友元函数的方式重载了输入输出运算符,类PersionA使用了普通函数重载了输入输出运算符。

#include <cstring>
#include <iostream>
using namespace std;

class Persion
{
public:
    //constructor
    Persion(const char *pname, unsigned int ag, double he,double we):age(ag),height(he),weight(we){strcpy(name,pname);}

    //operator overload : <<
    friend ostream& operator<<(ostream& out, const Persion& ref)
    {
        out<<ref.name<<"\t"<<ref.age<<"\t"<<ref.height<<"\t"<< ref.weight;
        return out;
    }
    //operator overload : >>
    friend istream& operator>>(istream& in, Persion& ref)
    {
        char name[40] = {0};
        unsigned int ag = 0;
        double he = 0;
        double we = 0;

        in>>name>>ag>>he>>we;

        //check that if the inputs succeeded
        if (in)
        {//Input Succeeded
            strcpy(ref.name, name);
            ref.age = ag;
            ref.height = he;
            ref.weight = we;
        }
        else
        {//Input Failed
        }

        return in;
    }
private:
    char name[40];
    unsigned int age;
    double height;
    double weight;
};

class PersionA
{
public:
    //constructor
    PersionA(const char *pname, unsigned int ag, double he,double we):age(ag),height(he),weight(we){strcpy(name,pname);}
    //GetData
    char* GetName(void){return name;}
    unsigned int& GetAge(void){return age;}
    double& GetHeight(void){return height;}
    double& GetWeight(void){return weight;}


private:
    char name[40];
    unsigned int age;
    double height;
    double weight;
};

//operator overload : <<
ostream& operator<<(ostream& out, PersionA& ref)
{
    out<<ref.GetName()<<"\t"<<ref.GetAge()<<"\t"<<ref.GetHeight()<<"\t"<<ref.GetWeight();
    return out;
}
//operator overload : >>
istream& operator>>(istream& in, PersionA& ref)
{
    char name[40] = {0};
    unsigned int ag = 0;
    double he = 0;
    double we = 0;

    in>>name>>ag>>he>>we;

    //check that if the inputs succeeded
    if (in)
    {//Input Succeeded
        strcpy(ref.GetName(), name);
        ref.GetAge() = ag;
        ref.GetHeight() = he;
        ref.GetWeight() = we;
    }
    else
    {//Input Failed
    }

    return in;
}
int main(void)
{
    Persion per("Jack", 20, 175, 65);
    cout << per << endl;
    cin>>per;
    cout << per << endl;

    PersionA perA("Jack", 20, 175, 65);
    cout << perA << endl;
    cin>>perA;
    cout << perA << endl;
    return 0;
}