MyString.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class MyString
{
public:
MyString();
MyString(int len);
MyString(const char* str);
MyString(const MyString& another);
~MyString();
//重载操作符[] << >> == != =
friend ostream& operator<<(ostream& os, MyString& s);
char& operator[](int index);
MyString& operator=(const MyString& another);
friend istream& operator>>(istream& is, MyString& s);
MyString operator+(MyString& another);
private:
int len;
char* str;
};
MyString.cpp
#include "MyString.h"
MyString::MyString()
{
this->len = 0;
this->str = NULL;//NULL等价于'\0'
}
MyString::MyString(int len)
{
}
MyString::MyString(const char* str)
{
if (str == NULL)
{
this->len = 0;
this->str = new char[0 + 1];
strcpy(this->str, "");//开辟一个空字符串
}
else
{
int len = strlen(str);
this->len = len;
this->str = new char[len + 1];
strcpy(this->str, str);
}
}
MyString::MyString(const MyString& another)
{
this->len = another.len;
this->str = new char[this->len + 1];
strcpy(this->str, another.str);
}
MyString::~MyString()
{
if (this->str)
{
cout << "~MyString()..." << endl;
delete this->str;
this->str = NULL;
this->len = 0;
}
}
char& MyString::operator[](int index)
{
return this->str[index];
}
MyString& MyString::operator=(const MyString& another)
{
if (this == &another)
{
return *this;
}
if (this->str)
{
delete[] this->str;
this->str = NULL;
this -> len = 0;
}
this->len = another.len;
this->str = new char[this->len + 1];
strcpy(this->str, another.str);
return *this;
}
ostream& operator<<(ostream& os, MyString& s)
{
os << s.str;
return os;
}
istream& operator>>(istream& is, MyString& s)
{
//1、将之前的字符串释放掉
if (s.str)
{
delete[] s.str;
s.str = NULL;
s.len = 0;
}
char temp_str[4096] = { 0 };
//2、通过cin开辟添加新的字符串
cin >> temp_str;
int len = strlen(temp_str);
s.str = new char[len + 1];
strcpy(s.str, temp_str);
s.len = len;
return is;
}
MyString MyString::operator+(MyString& another)
{
MyString temp;
int len = this->len + another.len;
temp.len = len;
temp.str = new char[len + 1];//开辟空间了,里面内容未知
memset(temp.str, 0, len + 1);
strcat(temp.str, this->str);
strcat(temp.str, another.str);
return temp;
}
main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include"MyString.h"
using namespace std;
int main(void)
{
MyString s1("abc");
MyString s2("123");
cout << (s1 + s2) << endl;//仿照string,(s1 + s2)应该返回一个MyString 匿名对象//?????????
//cout << s1 + s2 << endl;
cout << s1 << endl;
cout << s2 << endl;
return 0;
}
为什么52行代码显示C2679和E0349不对呢???????????????????????????(自定义了一个Mystring类,用法仿照string类,操作符 << 和 + 也已经声明和定义)