/*操作符重载(2)*/

#include "stdafx.h"
#include <iostream.h>
#include <string.h>

class MyInt
{
private:
    int   m_nData;
    char* m_pStr;
public:
    //
转换构造函数  带参构造
    MyInt( int nData )
    {
        m_nData = nData;
        m_pStr  = new char[2];
        m_pStr[0] = 'A';
        m_pStr[1] = 0;
    }
    virtual ~MyInt()
    {
        Release();
    }
    //
拷贝构造
    MyInt( const MyInt& Obj )
    {
        m_nData = Obj.m_nData;
        m_pStr  = new char[strlen(Obj.m_pStr)+sizeof(char)];
        strcpy(m_pStr,Obj.m_pStr);
    }
    //
转换运算符函数
    //
这格式,神了,返回值居然能放到后面

    operator int()
    {
        return m_nData;
    }
public:
    void Release()
    {
        if (m_pStr)
        {
            delete[] m_pStr;
            m_pStr = NULL;
        }
    }
    void SetData( int nData )
    {
        m_nData = nData;
    }
public:
    //a++
重载,友元没有this指针,所以多了个对象参数
    friend MyInt operator++(MyInt& Obj,int);
    //++a
重载友元没有this指针,所以多了个对象参数
    friend MyInt operator++(MyInt& Obj);
    //=
号重载
    MyInt &operator=( const MyInt& Obj )
    {
        //
如果是 a = a这种格式的话就直接返回
        if ( this == &Obj )
        {
            return *this;
        }
        m_nData = Obj.m_nData;       
        Release();       
        m_pStr  = new char[strlen(Obj.m_pStr)+sizeof(char)];       
        strcpy(m_pStr,Obj.m_pStr);       
        return *this;
    }
};

//a++
重载实现,友元没有this指针,所以多了个对象参数
MyInt operator++(MyInt &Obj,int)
{
    MyInt temp(Obj.m_nData);
    Obj.m_nData++;
    return temp;
}

//++a
重载实现,友元没有this指针,所以多了个对象参数
MyInt operator++(MyInt &Obj)
{
    Obj.m_nData++;
    return Obj;
}

int main(int argc, char* argv[])
{
    MyInt a(0);   
    //
基本数据类型  ----> 类类型  (转换构造函数)   
    //
类类型  ----> 基本数据类型  (转换运算符)   

    MyInt b(1);
    MyInt c(10);
   
    //cout
后面不能跟对象,所以a++调用了转换运算符函数
    cout << a++ << endl;   
    cout << ++a << endl;
   
    a = a;   
    //=
赋值运算符,运算右到左,返回值为左值
    (c = b = a).SetData(10);
   //
这里也要调用运算符函数
    cout << c << b << a << endl;
   
    return 0;
}

posted on 2010-02-01 20:32  o无尘o  阅读(174)  评论(0编辑  收藏  举报