(重載)多載運算子

因為上網查太多次了,每次又查到想翻書算了,翻書翻到覺得書寫得太多了。
所以乾脆自己來寫一篇簡單小筆記

operator系列

operator=
assignment
//String.h
class String{
public:
    //....
    String& operator=( const char*);
    String& operator=( const String&);
    //....
private:
    int _size;
    char *_string;
}
//String.cpp
String& String::operator=(const char* sobj)
{
    //...
    return *this;
}
operator()
function call
某個class代表某動作
//absInt.h
class absInt{
public:
    int operator()(int val)
    {
        int result = val < 0 ? -val : val;
        return result;
    }
}
//main.cpp
typedef vector::iterator iter_type;

iter_type transform(iter_type iter, iter_type last,
                    iter_type result, absInt func)
{
    while(iter != last)
        *result++ = func( *iter++ ); //invokes absInt::operator()
    return iter;
}

int main()
{
    int ia[] = {-0, 1, -1, -2 ,3, 5, -5, 8};
    vector ivec(ia, ia+8);

    transform(ivec.begin(), ivec.end(), ivec.begin(), absInt());
    //...
    return 0;
}
operator->
member access arrow
適用於Smart point class
//ScreenPtr.h
class ScreenPtr{
    //...
private:
    Screen *ptr;
public:
    ScreenPtr(Screen &s) : ptr(&s){} //construct
    void move(int , int);//keyin by myself
    Screen&  operator *(){ return *ptr;}
    Screen*  operator ->(){ return ptr;}
    //...
};
//main.cpp
int main()
{
    Screen p1//error

    Screen myScreen(4, 4);
    ScreenPtr ps( myScreen );  //ok by construct
    ps->move(2, 3);
    return 0;
}
operator++
operator--

分成前置版和後置版
//ScreenPtr.h
class ScreenPtr{
private:
    Screen *ptr;
public:
    Screen& operator++();    //prefix operators
    Screen* operator--();
    Screen& operator++(int); //postfix operators
    Screen& operator--(int);
    //...
};
//ScreenPtr.cpp
//prefix operators
Screen& ScreenPtr::operator++()
{
    //...
    return *++ptr;
}

Screen& ScreenPtr:: operator --()
{
    //...
    return *--ptr;
}

//postfix operators
Screen& ScreenPtr:: operator ++(int)
{
    //...
    return *++ptr;
}

Screen& ScreenPtr:: operator --(int)
{
    //...
    return *--ptr;
}
operator new
operator delete

class ScreenPtr{
private:
    Screen *ptr;
public:
    void*  operator new(size_t);
    void   operator delete(void*);
    //...
};
operator new[] 
operator delete[]

//--------------------
operator<
//String.h
class String{
public:
    //....
    String& operator=( const char*);
    String& operator=( const String&);
    int GetInt();
    //....
private:
    int _size;
}
//String.cpp
bool operator<(const ScreenPtr& pStr) const
{ 
    return (GetInt() <  pStr.GetInt() );
}
operator==
//String.cpp
bool operator==(const ScreenPtr& pStr)const
{
    return (GetInt() ==  pStr.GetInt() );
}

沒有留言:

張貼留言

(什麼是留言欄訊息?)