目录
一、使用到的知识:
1、类的创建;
2、类内的构造函数、复制构造函数和析构函数;
3、类内运算符重载函数([]、+、=);
4、全局运算符重载函数(<<);
二、函数实现
#include <iostream>
#include <cstring>
using namespace std;
class MyString{
private:
char* my_string;
public:
// 无参空构造
MyString(){
this->my_string = new char[1];
this->my_string[0] = '\0';
cout << "无参空构造函数" << endl;
}
// 有参构造函数
MyString(const char* m_string){
int len = sizeof (m_string);
this->my_string = new char[len + 1];
memmove(this->my_string,m_string,len);
this->my_string[len] = '\0';
cout << "有参构造函数" << endl;
}
// 拷贝构造
MyString(const MyString& other){
int len = sizeof (other.my_string);
this->my_string = new char[len + 1];
memmove(this->my_string,other.my_string,len);
this->my_string[len] = '\0';
cout << "拷贝构造函数" << endl;
}
// 析构函数
~MyString(){
delete []my_string;
this->my_string = nullptr;
cout << "析构函数" << endl;
}
// get方法
char* get_my_string()const{
return this->my_string;
}
// =运算符重载函数
MyString& operator=(const MyString& other){
cout << "=运算符重载函数" << endl;
if(this == &other){
return *this;
}
int len = strlen(other.my_string);
if(this->my_string != nullptr){
delete []this->my_string;
this->my_string = new char[len + 1];
}else {
this->my_string = new char[len + 1];
}
memmove(this->my_string,other.my_string,len);
return *this;
}
// []运算符的重载
char operator[](int index){
cout << "[]运算符的重载" << endl;
if(index < 0 || (index >= (int)strlen(this->my_string))){
cout << "index值越界" << endl;
}
return this->my_string[index];
}
// +号运算符的重载
MyString operator+(const MyString& other){
cout << "+号运算符的重载" << endl;
int this_len = strlen(this->my_string);
int other_len = strlen(other.my_string);
char *temp = new char[this_len + other_len + 1];
memmove(temp,this->my_string,this_len);
memmove(temp + this_len,other.my_string,other_len);
temp[this_len + other_len] = '\0';
MyString my_temp = temp;
delete []temp; //释放中间变量
return my_temp;
}
};
//全局<<运算符的重载函数
ostream& operator<<(ostream& cout,const MyString& other){
cout <<other.get_my_string();
cout << "全局<<运算符的重载函数" << endl;
return cout;
}
int main()
{
MyString str1;
cout << "-----------------------------" << endl;
str1 = "123ancANC";
cout << "-----------------------------" << endl;
MyString str2("hello world!");
cout << "-----------------------------" << endl;
MyString str3 = "Happy forever!";
cout << "-----------------------------" << endl;
MyString str4 = str3;
cout << "-----------------------------" << endl;
cout << str3[1] << endl;
cout << "-----------------------------" << endl;
cout << str2 + str3 << endl;
cout << "-----------------------------" << endl;
return 0;
}
三、主要事项
1、等号运算符的重载函数中,注意判断等号两边的指针是否相同,判断等号左边是否创建空间、使用引用减少调用构造函数的次数以提高效率。
2、加号运算符的重载函数中,注意释放中间变量,以免造成内存泄漏。
四、总结
作为C++入门基础常考面试题,注意掌握class的构建和基本构造函数、各类重载函数的使用。