赋值运算符的重载

1.有时候希望赋值运算符两边的类型可以不匹配,比如说char*类型的字符串赋值给字符串对象

2.赋值运算符“=”只能重载为成员函数

#include <iostream>
#include <string.h>
#include <iomanip>

using namespace std;

class String
{
private:
    char* str;
public:
    String ():str(new char[1]){ str[0]=0; }
    const char *c_str(){ return str }
    String & operator=(const char* s);
    ~String() { delete[] str; }
};

String & String::operator=(const char* s)
{
    delete[] str;//清空当前指针指向的内存
    str=new char[strlen(s)+1];
    strcpy(str,s);
    return *this;
}

3.深拷贝和浅拷贝

#include <iostream>
#include <string.h>
#include <iomanip>

using namespace std;

class String
{
private:
    char* str;
public:
    String ():str(new char[1]){ str[0]=0; }
    const char *c_str(){ return str }
    String & operator=(const char* s);
    ~String() { delete[] str; }
    String (const String& s);
};

String String::String(const String& s)
{
    //delete[] str;拷贝构造函数被调用,不调用构造函数,不用delete
    str=new char[strlen(s.str)+1];
    strcpy(str,s.str);
}

String & String::operator=(const char* s)
{
    delete[] str;//清空当前指针指向的内存
    str=new char[strlen(s)+1];
    strcpy(str,s);
    return *s;
}

String & String::operator=(const String &s)
{
    if(this==&s)
    {
        return *this;
    }//防止s=s
    delete[] str;
    str=new char[strlen(s.str)+1];
    strcpy(str,s.str);
    return *this;
}

4.运算符重载为友元函数

成员函数不能满足要求,普通函数又不能访问私有成员变量

成员函数只能满足c=c+5,不能满足c=5+c;后者需要重载为友元函数才可以。

5.运算符重载示例(vector)

#include <iostream>
#include <string.h>
#include <iomanip>

using namespace std;

class CArray
{
    int size;
    int *ptr;
public:
    CArray(int s=0);
    CArray(const CArray &a);
    ~CArray();
    void push_back(int v);
    CArray& operator=(const CArray &a);
    int& operator[](int i);
    int length(){ return size; }
};

CArray::CArray(int s):size(s)
{
    if(s==0)
    {
        ptr=NULL;
    }
    else
    {
        ptr=new int[s];
    }
}

CArray::CArray(const CArray & a)
{
    if(!a.ptr)
    {
        ptr=NULL;
        size=0;
        return;
    }
    ptr=new int[a.size];
    memcpy(ptr,a.ptr,sizeof(int)*a.size);
    size=a.size;
}

CArray::~CArray()
{
    if(ptr)
    {
        delete[] ptr;
    }
}

CArray& CArray::operator=(const &CArray a)
{
    if(ptr==a.ptr)
    {
        return *this;
    }
    if(a.ptr==NULL)
    {
        if(ptr)
        {
            delete[] ptr;
        }
        ptr=NULL;
        size=0;
        return *this;
    }
    if(size<a.size)
    {
        if(ptr)
        {
            delete[] ptr;
        }
        ptr=new int[a.size];
    }
    memcpy(ptr,a.ptr,sizeof(int)*a.size);
    size=a.size;
    return *this;
}

void CArray::push_back(int v)
{
    if(ptr)
    {
        int *tmpPtr=new int[size+1];
        memccpy(tmpPtr,ptr,sizeof(int)*size);
        delete[] ptr;
        ptr=tmpPtr;
    }
    else
    {
        ptr=new int;
    }
    ptr[size++]=v;
}

int& CArray::operator[](int i)
{
    return ptr[i];
}
原文地址:https://www.cnblogs.com/-Asurada-/p/10668245.html