#include <iostream>
#include <iomanip>
class Mystring
{
private:
char* str; //记录c风格的字符串
int size; //记录字符串的实际长度
char c;
public:
Mystring();
Mystring(const char* s);
~Mystring();
Mystring(const Mystring& other);
Mystring& operator=(const Mystring& other);
int getsize();
const char* c_str() const;
char& at(int pos);
inline bool empty() const;
};
#include "Rect.h"
#include <string.h>
Mystring::Mystring():size(20)
{
str = new char[size];
strcpy(str, "");
std::cout << "无参"<< std::endl;
}
Mystring::Mystring(const char* s)
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
std::cout << "有参"<< std::endl;
}
Mystring::~Mystring()
{
//std::cout << this << std::endl;
delete []str;
}
Mystring::Mystring(const Mystring& other)
{
size = other.size;
c = other.c;
str = new char[size + 1];
strcpy(str, other.str);
std::cout << "调用了深拷贝构造函数" << std::endl;
}
Mystring& Mystring::operator=(const Mystring& other)
{
this->size = other.size;
strcpy(this->str,other.str);
this->c = other.c;
std::cout << "调用了深拷贝赋值函数" << std::endl;
return *this;
}
int Mystring::getsize()
{
return size;
}
char& Mystring::at(int pos)
{
std::string s = str;
if (pos < 0 || pos >= s.size())
{
std::cout << "越界访问" << std::endl;
}
c = s.at(pos);
return c;
}
inline bool Mystring::empty() const
{
std::string s = str;
return s.empty();
}
const char* Mystring::c_str() const
{
return str;
}
#include <iostream>
#include <string>
#include "Rect.h"
int main()
{
Mystring s1("hello word!");
Mystring s2(s1);
std::cout << s1.c_str() << std::endl;
std::cout << s2.c_str() << std::endl;
Mystring s3;
s3 = s1;
std::cout << s3.c_str() << std::endl;
return 0;
}