自己实现String类

45 篇文章 0 订阅
31 篇文章 1 订阅

资源来自 b站视频:

              探讨C++常见问题      --  授课者:今夜有风      (AV33683760)

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class String 
{
public:
	String(const char* str);//默认构造
	String(const String& str);//拷贝构造
	String& operator=(const String& str);//赋值函数
	~String();//析构
	char* m_data;
};

String::String(const char* str)
{
	if (str == NULL)
	{
		m_data = new char[1];
		m_data[0] = '\0';		
	}
	else
	{
		m_data = new char[strlen(str)+1];
		strcpy(m_data, str);
	}
}

String::String(const String& str)
{	
	m_data = new char[strlen(str.m_data) + 1];
	strcpy(m_data, str.m_data);	
}

String & String::operator=(const String &str)
{
	//String A;
	//String B = A;
	if (this == &str)
	{
		return *this;
	}
	//删除原来地数据
	delete[]m_data;
	m_data = new char[strlen(str.m_data) + 1];
	strcpy(m_data, str.m_data);
	return *this;
}

String::~String()
{
	delete[]m_data;
	m_data = NULL;
}

int main()
{
	String A("THIS IS WORLD");
	String C(A);
	String B("少说两句废话,多敲几行代码");
	C = B;

	cout << "hello" << endl;
	cout << "A.m_data:" << A.m_data << endl;
	cout << "C.m_data:" << C.m_data << endl;
	cout << "B.m_data:" << B.m_data << endl;
	return 0;
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++中的string是一个用于处理字符串的标准库。它提供了一系列成员函数和操作符重载,使得字符串的操作更加方便和高效。 C++中的string位于命名空间std中,因此在使用之前需要包含头文件< string >。 下面是一个简单的示例,展示了如何使用string来创建、初始化和操作字符串: ```cpp #include <iostream> #include <string> int main() { // 创建一个空字符串 std::string str; // 初始化字符串 std::string greeting = "Hello, world!"; // 获取字符串长度 int length = greeting.length(); std::cout << "Length: " << length << std::endl; // 连接字符串 std::string name = "Alice"; std::string message = greeting + " My name is " + name; std::cout << "Message: " << message << std::endl; // 获取子串 std::string substring = message.substr(7, 5); std::cout << "Substring: " << substring << std::endl; // 查找子串 size_t position = message.find("world"); if (position != std::string::npos) { std::cout << "Found at position: " << position << std::endl; } else { std::cout << "Not found" << std::endl; } return 0; } ``` 上述示例中,我们首先创建了一个空字符串`str`,然后使用赋值运算符将字符串"Hello, world!"赋给了变量`greeting`。接着,我们使用`length()`函数获取了字符串的长度,并使用`+`运算符将多个字符串连接起来形成新的字符串。我们还使用`substr()`函数获取了字符串的子串,并使用`find()`函数查找了子串在原字符串中的位置。 除了上述示例中的操作,string还提供了许多其他有用的成员函数和操作符重载,如插入、删除、替换、比较等。你可以参考C++的官方文档或其他相关资料来了解更多关于string的详细信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值