剑指offer——赋值运算符函数

#include<iostream>
using namespace std;

class String
{
public:
    String(char * pData = NULL);
    String(const String& str);
    ~String();
    String& operator=(const String& str);
    void print();
private:
    char * m_pData;
};

String::String(char * pData)
{
    if (pData == NULL)
    {
        m_pData = new char[1];
        m_pData[0] = '\0';
    }
    else
    {
        int length = strlen(pData);
        m_pData = new char[length + 1];
        strcpy(m_pData, pData);
    }
}

String::String(const String& str)
{
    int length = strlen(str.m_pData);
    m_pData = new char[length + 1];
    strcpy(m_pData, str.m_pData);
}

String::~String()
{
    delete[] m_pData;
}

/*
//常规方法
String& String::operator=(const String& str)
{
    if (this == &str)
        return *this;
    delete[] m_pData;
    m_pData = NULL;
    m_pData = new char[strlen(str.m_pData) + 1];
    strcpy(m_pData, str.m_pData);
    return *this;
}
*/

/*
//先分配,再释放
String& String::operator=(const String& str)
{
    if (this == &str)
        return *this;

    char * temp = new char[strlen(str.m_pData) + 1];;

    delete[] m_pData;
    m_pData = temp;
    strcpy(m_pData, str.m_pData);
    return *this;
}
*/

//创建临时变量
String& String::operator=(const String& str)
{
    if (this == &str)
        return *this;

    String ss(str);

    char * temp = ss.m_pData;
    ss.m_pData = m_pData;
    m_pData = temp;

    return *this;
}


//测试代码
void String::print()
{
    cout << m_pData << endl;
}

void Test1()
{
    cout << "Test1 begins:\n";
    char * text = "hello world";
    String str1(text);
    String str2;
    str2 = str1;
    cout << "The expected result is: " << text << endl;
    cout << "The actual result is:";
    str2.print();
    cout << endl;
}

//赋值给自己
void Test2()
{
    cout << "Test1 begins:\n";
    char * text = "hello world";
    String str1(text);
    str1 = str1;
    cout << "The expected result is: " << text << endl;
    cout << "The actual result is:";
    str1.print();
    cout << endl;
}

//连续赋值
void Test3()
{
    cout << "Test1 begins:\n";
    char * text = "hello world";
    String str1(text);
    String str2, str3;
    str3 = str2 = str1;

    cout << "The expected result is: " << text << endl;
    cout << "The actual result is:";
    str2.print();
    cout << endl;

    cout << "The expected result is: " << text << endl;
    cout << "The actual result is:";
    str3.print();
    cout << endl;
}

int main()
{
    Test1();
    Test2();
    Test3();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值