侯捷C++(String类)
注意事项(class with pointer members)#
Big Three,三个特殊函数:析构函数、拷贝构造函数、拷贝赋值函数。
代码(String类)#
#include <iostream>
#include <bits/c++config.h>
#include <string.h>
using namespace std;
class String
{
public:
//构造函数,只有构造函数可以用列表初始化
inline String(const char* cStr = " ") : m_data(new char[strlen(cStr) + 1])
{
strcpy(m_data, cStr);
}
//拷贝构造函数
inline String(const String& otherStr) : m_data(new char[strlen(otherStr.m_data) + 1])
{
strcpy(m_data, otherStr.m_data);
}
//析构函数
inline ~String()
{
delete []m_data;
}
//追加函数
String& append(const String& otherStr);
//得到m_data
inline char* getChar() const { return m_data; }
//拷贝赋值函数
String& operator = (const String& otherStr);
private:
char* m_data;
};
inline String& String::append(const String& otherStr)
{
char *pTmp = new char[strlen(this->m_data) + strlen(otherStr.m_data) +1];
strcpy(pTmp, this->m_data);
strcat(pTmp, otherStr.m_data);
m_data = pTmp;
return *this;
}
inline String& String::operator = (const String& otherStr)
{
//检测自我赋值,否则会删除自己
if (this == &otherStr)
{
return *this;
}
else
{
delete []m_data;
m_data = new char[strlen(otherStr.m_data) + 1];
strcpy(m_data, otherStr.m_data);
return *this;
}
}
inline ostream& operator << (ostream& os, const String& str)
{
return os << str.getChar() << endl;
}
int main()
{
String s1("hello");
cout << "构造函数:" << s1;
String s2(s1);
cout << "拷贝构造函数:" << s2;
String s3 = s2;
cout << "拷贝赋值函数:" << s3;
String s4;
s4.append("hello").append(" world!");
cout << "append函数:" << s4;
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具