重載操作符與轉換

重載操作符是具有特殊名稱的函數:保留字operator後接需定義的操作符符號。
重載操作符必須具有一個類類型的操作數
重載操作符的優先級和結合性是固定的
重載操作符不具備短路求值特性
當重載操作符作爲成員函數時,其隱含的this指針限定爲第一個操作數,一般將賦值操作符定義爲成員函數,算術和關係操作符定義爲友員函數。=,[], ->,()一般只能定義爲成員函數,改變對象狀態如自增,自減,解引用一般定義爲成員函數, +=一般定義爲成員函數,對稱的運算符一般定義爲非成員函數。
編譯器會自動合成賦值操作符,取地址操作符,逗號操作符的默認版本
一個例子:

#pragma once
#include <string.h>
#include <string>
#include <iostream>
class MyString
{
public:
    MyString(const char *str = NULL);
    MyString(const MyString &rhs);
    MyString & operator=(const MyString &rhs);
    virtual ~MyString(void);
    MyString & operator+=(const MyString &rhs);
    friend std::ostream & operator <<(std::ostream &os,const MyString &s);
    friend std::istream & operator >>(std::istream &is,MyString &s);
private:
    char *m_data;
    //std::string str;
};

MyString  operator+(const MyString &,const MyString &);

#include "MyString.h"


MyString::MyString(const char *str)
{
    if (str == NULL)
    {
        m_data = NULL;
        return;
    }
    m_data = new char[strlen(str) + 1];
    strcpy(m_data,str);
}

MyString::~MyString(void)
{
    delete []m_data;
    m_data = NULL;
}

MyString::MyString(const MyString &rhs)
{
    m_data = new char[strlen(rhs.m_data) + 1];
    strcpy(m_data,rhs.m_data);
}
MyString & MyString::operator=(const MyString &rhs)
{
    if (this == &rhs)
    {
        return *this;
    }
    delete []m_data;
    m_data = new char[strlen(rhs.m_data) + 1];
    strcpy(m_data,rhs.m_data);
    return *this;
}

MyString & MyString::operator+=(const MyString &rhs)
{
    char *temp=m_data;
    int len = strlen(m_data) + strlen(rhs.m_data);
    temp = new char[len + 1];  
    if(!temp)  
    {  
        return *this;
    }  
    strcpy(m_data,temp);  
    strcat(m_data,rhs.m_data);  
    delete[] temp;  
    return *this;  
}

std::ostream & operator <<(std::ostream &os,const MyString &s)
{
    os << s.m_data;
    return os;
}
std::istream & operator >>(std::istream &is,MyString &s)
{
    is >> s.m_data;
    if (is)
    {
    }else
    {
        s.m_data = NULL;
    }
    return is;
}
MyString operator+(const MyString &str1,const MyString &str2)
{
    MyString str(str1);
    str += str2;
    return str;
}

轉換操作符,轉換操作符的格式
operator type();
如: operator int(){return 0;}
轉換操作符必須是成員函數,沒有返回值,形參爲空
函數調用操作符必須爲成員函數
bool operator()(int a){return a > 0;}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章