String类的运算符重载

百度云课堂上的视频课,记下代码,复习用。

首先定义一个类,iotekstring.h

#ifndef IOTEK_STRING_H
#define IOTEK_STRING_H
#include<iostream>
namespace iotek{
    class String{
    public:
        String(const char * = NULL); \\对输入变量进行初始化
        ~String();
        String(const String&);//拷贝构造函数
        //String a; a=b
        String& operator=(const String&);//赋值运算符
        //String a; a = "Hello"
        String& operator=(const char*);//赋值运算符
        inline const char* data() const
        {
            return m_data;
        }
    private:
        char *m_data;
    };
}
#endif**


对成员函数进行定义,iotekstring.cpp

#include "iotekstring.h"
#include <string.h>
#include <iostream>
using namespace::std;
using namespace::iotek;

namespace iotek{

    String::String(const char* str)
    {
        if (NULL == str){
            m_data = new char[1];
            *m_data = '\0';
        }
        else{
            int length = strlen(str);
            m_data = new char[length + 1];
            strcpy_s(m_data, length+1, str);
        }
    }

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

    String::String(const String &other)
    {
        //深拷贝
        int length = strlen(other.m_data);
        m_data = new char[length + 1];
        strcpy_s(m_data, length+1, other.m_data);

    }
    //赋值运算符
    String & String::operator=(const String &other)
    {
        if (this == &other){
            return *this;
        }
        delete[] m_data;

        int length = strlen(other.m_data);
        m_data = new char[length + 1];
        strcpy_s(m_data, length+1,  other.m_data);
        return *this;
    }

    String & String::operator=(const char* other)
    {
        delete[] m_data;
        if (other == NULL){
            m_data = new char[1];
            *m_data = '\0';
        }
        else{
            int length = strlen(other);
            m_data = new char[length + 1];
            strcpy_s(m_data, length+1, other);
        }
        return *this;
    }
}//end of iotek



主函数,main.cpp
#include "iotekstring.h"
#include <iostream>
using namespace::std;
using namespace::iotek;

int main(int argc, char* argv[])
{
    String s1("hello");
    String s2 = s1;  //调用拷贝构造函数
    String s3 = "world";

    s3 = s1; //调用赋值运算符
    s3 = "world";

    cout << "s3 = " << s3.data() << endl;

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值