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


    
    //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;
    }
    
    
    
  • 相关阅读:
    [轉]Flex实现代码分离mxml/as
    [轉]PHP执行MYSQL存储过程报错:Commands out of sync; you can't run this command now 问题的解决
    [轉]mysqli & pdo使用实例和详解
    JSON格式驗證以及格式說明
    [轉]can't return a result set in the given context及参数解释
    PHP ADODB資源
    [轉]Virtual PC 网络设置(Networking)
    [轉]20个非常有用的PHP类库
    [轉]MySQL存储过程 ERROR Handler 异常处理
    [轉]如何通过Jquery获取radio的值
  • 原文地址:https://www.cnblogs.com/sunstars/p/3999278.html
Copyright © 2020-2023  润新知