C++自定义MyString类型字符串,重载相应的操作符
程序员文章站
2022-05-24 19:08:44
自定义MyString类型字符串,重载相应的操作符;
#include"iostream" //包含C++的头文件。
#include"MyS...
自定义MyString类型字符串,重载相应的操作符;
#include"iostream" //包含C++的头文件。 #include"MyString.h" using namespace std; //使用标准的std命名空间(在这个空间里面定义了很多的标准定义) //在iostream中没有引入std命名空间,在此所以要自己写;如果不写则需要显示引入std; void main(){ /* MyString s1; MyString s2("hahahaha"); MyString s3(NULL); MyString s4 = s2; MyString *s5 = new MyString(); */ MyString s2("hahahaha"); MyString s6 = "heiheihei";//这种调用的是有参构造函数; s6 = s2;//这种是复制内容 cout << s6.getString() << endl; s6 = "heheheh";//也是复制内容,以上两种都需要重载等号操作符; cout << s6.getString() << endl; s6[1] = 'A';//重载[]运算符; cout << s6[1] << endl; system("pause"); }
头文件:
#pragma once class MyString { public: MyString(); MyString(const char* str); MyString(const MyString & str); ~MyString(); char* getString(); MyString& operator=(MyString& s); MyString& operator=(char* s); char& operator[](int position); private: int len; char* mystr; };
MyString.cpp
#include "MyString.h" #include using namespace std; MyString::MyString() { cout << "无参构造函数" << endl; len = 0; mystr = new char[len + 1]; strcpy(mystr,""); } MyString::MyString(const char* str) { cout << "有参构造函数" << endl; if (str==NULL) { len = 0; mystr = new char[len + 1]; strcpy(mystr, ""); } else { len = strlen(str); mystr = new char[len + 1]; strcpy(mystr, str); } } MyString::MyString(const MyString & str) { cout << "拷贝构造函数" << endl; len = str.len; mystr = new char[len+1]; strcpy(mystr,str.mystr); } MyString& MyString::operator=(MyString& s) { if (mystr!=NULL) { delete[] mystr; len = 0; } mystr = new char[s.len + 1]; strcpy(mystr,s.mystr); len = s.len; return *this; } MyString& MyString::operator=(char* s) { if (s==NULL) { len = 0; mystr = new char[len + 1]; strcpy(mystr,""); } else { if (mystr != NULL) { delete[] mystr; len = 0; } len = strlen(s); mystr = new char[len + 1]; strcpy(mystr, s); } return *this; } char* MyString::getString() { return mystr; } //重载[]; char& MyString::operator[](int position) { return mystr[position]; } MyString::~MyString() { if (mystr!=NULL) { delete [] mystr; mystr = NULL; } len = 0; }
总结:一个类中如果有指针的话,一般需要写拷贝构造函数和=重载运算符;这两个涉及到内存析构问题(深浅拷贝);