操作符重载(++,+,输入输出,强制类型转换)


//Interge.h
#include <iostream>
using namespace std;

class Interge
{
        friend ostream & operator<< (ostream &, const Interge &);//由于包含有隐式的参数,所以该函数只能用作friend,而友元在类的任何位置都可以定义(不属于类的成员),一般放在这里
        friend istream & operator>> (istream &, Interge &);
    public:
        Interge ();
        Interge (int);
       // Interge (const Interge &);
        Interge & operator= (int);
       // Interge & operator= (const Interge &);
       //~Interge();

        Interge & operator+ (const Interge &);
        Interge & operator++ ();//++i
        Interge operator++ (int);//i++
        operator int()//类型转化
        {return date_;}
        
        int get_interge() const
        {return date_;}
    private:
        int date_;
};


//Interge.cpp
#include "Interge.h"

Interge::Interge()
    :date_(0)
{
}

Interge::Interge(int i)
    :date_(i)
{
}

/*Interge::Interge(const Interge &intg)
{
    date_ = intg.date_;
}

Interge & Interge::operator= (const Interge &intg)
{
    date_ = intg.date_;
    return *this;
}
*/
Interge & Interge::operator= (int i)
{
    date_ = i;
    return *this;
}

Interge & Interge::operator+ (const Interge &intg)
{
    date_+= intg.get_interge();
    return *this;
}

Interge & Interge::operator++ ()
{
    ++date_;
    return *this;
}

Interge Interge::operator++ (int)
{
    Interge tmp(*this);
    ++date_;
    return tmp;
}
ostream & operator<< (ostream &os, const Interge &intg)
{
    return os << intg.date_;
}

istream & operator>> (istream &is, Interge &intg)//输入不能为const
{
    int tmp = intg.date_;
    is >> intg.date_;
    if (!is)//输入状态良好的情况下,is才是true
    {
        intg.date_ = tmp;
    }
    return is;
}

//main.cc
#include "Interge.h"
using namespace std;

int main(int argc, const char *argv[])
{
    Interge I1(1);
    Interge I2(I1);
    Interge I3,I4;

    I4 = I3 = I1;
    cout << I1 << I2 << I3 << I4 << endl;
    cin >> I4;
    cout << ++I4 << I4++ << I4 << endl;
    cout << I1 + I2 << endl;
    return 0;
}


posted on 2014-09-29 00:19  __hello world  阅读(94)  评论(0编辑  收藏  举报

导航