=, [], () 和 -> 操作符只能通过成员函数进行重载
>只能通过全局函数配合友元函数进行重载
不要重载 && 和 || 操作符,因为无法实现短路规则
常规建议:
MyString.h
#define _CRT_SECURE_NO_WARNINGS
#pragma once
#include
using namespace std;
class MyString
{
friend ostream& operator(istream& in, MyString& str);
public:
MyString(const char *);
MyString(const MyString&);
~MyString();
char& operator[](int index); //[]重载
//=号重载
MyString& operator=(const char * str);
MyString& operator=(const MyString& str);
//字符串拼接 重载+号
MyString operator+(const char * str );
MyString operator+(const MyString& str);
//字符串比较
bool operator== (const char * str);
bool operator== (const MyString& str);
private:
char * pString; //指向堆区空间
int m_Size; //字符串长度 不算'\0'
};
MyString.cpp
#include "MyString.h"
//左移运算符
ostream& operator buf;
str.pString = new char[strlen(buf) + 1];
strcpy(str.pString, buf);
str.m_Size = strlen(buf);
return in;
}
//构造函数
MyString::MyString(const char * str)
{
this->pString = new char[strlen(str) + 1];
strcpy(this->pString, str);
this->m_Size = strlen(str);
}
//拷贝构造
MyString::MyString(const MyString& str)
{
this->pString = new char[strlen(str.pString) + 1];
strcpy(this->pString, str.pString);
this->m_Size = str.m_Size;
}
//析构函数
MyString::~MyString()
{
if (this->pString!=NULL)
{
delete[]this->pString;
this->pString = NULL;
}
}
char& MyString::operator[](int index)
{
return this->pString[index];
}
MyString& MyString::operator=(const char * str)
{
if (this->pString != NULL){
delete[] this->pString;
this->pString = NULL;
}
this->pString = new char[strlen(str) + 1];
strcpy(this->pString, str);
this->m_Size = strlen(str);
return *this;
}
MyString& MyString::operator=(const MyString& str)
{
if (this->pString != NULL){
delete[] this->pString;
this->pString = NULL;
}
this->pString = new char[strlen(str.pString) + 1];
strcpy(this->pString, str.pString);
this->m_Size = str.m_Size;
return *this;
}
MyString MyString::operator+(const char * str)
{
int newsize = this->m_Size + strlen(str) + 1;
char *temp = new char[newsize];
memset(temp, 0, newsize);
strcat(temp, this->pString);
strcat(temp, str);
MyString newstring(temp);
delete[] temp;
return newstring;
}
MyString MyString::operator+(const MyString& str)
{
int newsize = this->m_Size + str.m_Size + 1;
char *temp = new char[newsize];
memset(temp, 0, newsize);
strcat(temp, this->pString);
strcat(temp, str.pString);
MyString newstring(temp);
delete[] temp;
return newstring;
}
bool MyString::operator==(const char * str)
{
if (strcmp(this->pString, str) == 0 && strlen(str) == this->m_Size){
return true;
}
return false;
}
bool MyString::operator==(const MyString& str)
{
if (strcmp(this->pString, str.pString) == 0 && str.m_Size == this->m_Size){
return true;
}
return false;
}
TestMyString.cpp
void test01()
{
MyString str("hello World");
cout
关注
打赏