1. 程式人生 > >C++ 實現字串類(過載運算子)

C++ 實現字串類(過載運算子)

CNString.h:

#include <iostream>
#include <cstring>

#ifndef CNSTRING_H
#define CNSTRING_H
class CNString
{
public:
    CNString& operator=(const CNString &cn);//重構=
    CNString operator+(const CNString &cn);//重構+
    char operator[](int index);//重構[]
    bool operator<(const CNString &cn);//重構<
    bool operator>(const CNString &cn);//重構>
    bool operator==(const CNString &cn);//重構==
    CNString();//預設建構函式
    CNString(const char *s);//建構函式
    CNString(const CNString &c);//拷貝建構函式
    ~CNString();//解構函式
    void display();//輸出資料
public:
    char *m_s;
};
#endif //TEST1_CNSTRING_H

CNString.cpp:

#include "CNString.h"
//過載運算子:=
CNString& CNString::operator=(const CNString &cn)
{
    this->m_s = new char[strlen(cn.m_s)+1];
    strcpy(this->m_s,cn.m_s);
    return *this;
}
//過載運算子:+
CNString CNString::operator+(const CNString &cn)
{
    CNString temp;
    temp.m_s = new char[strlen(this->m_s)+strlen(cn.m_s)+1];
    strcpy(temp.m_s, this->m_s);
    strcat(temp.m_s, cn.m_s);
    return temp;
}
//過載運算子:[]
char CNString::operator[](int index)
{
    if(index >= strlen(this->m_s))
    {
        return '\0';
    }
    return this->m_s[index];
}
//過載運算子:<
bool CNString::operator<(const CNString &cn)
{
    if(strcmp(this->m_s, cn.m_s) < 0)
    {
        return true;
    }
    return false;
}
//過載運算子:>
bool CNString::operator>(const CNString &cn)
{
    if(strcmp(this->m_s, cn.m_s) > 0)
    {
        return true;
    }
    return false;
}
//過載運算子:==
bool CNString::operator==(const CNString &cn)
{
    if(strcmp(this->m_s, cn.m_s) == 0)
    {
        return true;
    }
    return false;
}
//預設建構函式
CNString::CNString()
{
    this->m_s = new char('\0');
}
//建構函式
CNString::CNString(const char *s) {
    m_s = new char[strlen(s)+1];
    strcpy(m_s, s);
}
//拷貝建構函式
CNString::CNString(const CNString &c)
{
    m_s = new char[strlen(c.m_s)+1];
    strcpy(m_s,c.m_s);
}
//解構函式
CNString::~CNString()
{
    delete m_s;
	m_s = nullptr;
}
//輸出資料
void CNString::display()
{
    std::cout << m_s << std::endl;
}

main.cpp

int main()
{
	
	CNString cn("def");
	CNString cp("abc");
	CNString cn1(cn);
	CNString cn2 = "ghj";
	CNString cn3 = cn2 + cn;
	CNString cn4 = cn3 + cn1;
	cn1.display();
	cn.display();
	cn2.display();
	cn3.display();
	std::cout << cn[2] << std::endl;
	if (cn > cp)
	{
		std::cout << "cn > cp" << std::endl;
	}
	if (cn < cp)
	{
		std::cout << "cn < cp" << std::endl;
	}
	if (cn == cn1)
	{
		std::cout << "cn == cn1" << std::endl;
	}
	cn4.display();
	system("pause");
    return 0;
}