详解C++句柄类
class MyString
{
public:
// 默认构造函数
MyString()
{
std::cout << "MyString()" << std::endl;
buf_ = new char[1];
buf_[0] = '0';
len_ = 0;
}
// const char*参数的构造函数
MyString(const char* str)
{
std::cout << "MyString(const char* str)" << std::endl;
if (str == nullptr)
{
len_ = 0;
buf_ = new char[1];
buf_[0] = '0';
}
else
{
len_ = strlen(str);
buf_ = new char[len_ + 1];
strcpy_s(buf_, len_ + 1, str);
}
}
// 拷贝构造函数
MyString(const MyString& other)
{
std::cout << "MyString(const MyString& other)" << std::endl;
len_ = strlen(other.buf_);
buf_ = new char[len_ + 1];
strcpy_s(buf_, len_ + 1, other.buf_);
}
// str1 = str2;
const MyString& operator=(const MyString& other)
{
std::cout << "MyString::operator=(const MyString& other)" << std::endl;
// 判断是否为自我赋值
if (this != &other)
{
if (other.len_ > this->len_)
{
delete[]buf_;
buf_ = new char[other.len_ + 1];
}
len_ = other.len_;
strcpy_s(buf_, len_ + 1, other.buf_);
}
return *this;
}
// str = "hello!";
const MyString& operator=(const char* str)
{
assert(str != nullptr);
std::cout << "operator=(const char* str)" << std::endl;
size_t strLen = strlen(str);
if (strLen > len_)
{
delete[]buf_;
buf_ = new char[strLen + 1];
}
len_ = strLen;
strcpy_s(buf_, len_ + 1, str);
return *this;
}
// str += "hello"
void operator+=(const char* str)
{
assert(str != nullptr);
std::cout << "operator+=(const char* str)" << std::endl;
if (strlen(str) == 0)
{
return;
}
size_t newBufLen = strlen(str) + len_ + 1;
char* newBuf = new char[newBufLen];
strcpy_s(newBuf, newBufLen, buf_);
strcat_s(newBuf, newBufLen, str);
delete[]buf_;
buf_ = newBuf;
len_ = strlen(buf_);
}
// 重载 ostream的 <<操作符 ,支持 std::cout << MyString 的输出
friend std::ostream& operator<<(std::ostream &out, MyString& obj)
{
out << obj.c_str();
return out;
}
// 返回 C 风格字符串
const char* c_str()
{
return buf_;
}
// 返回字符串长度
size_t length()
{
return len_;
}
~MyString()
{
delete[]buf_;
buf_ = nullptr;
}
private:
char* buf_;
size_t len_;
};