C++面试题:String类的实现
来源:互联网 发布:mac搜索文件命令 编辑:程序博客网 时间:2024/06/03 20:51
#include<iostream>
#include<cstring>
using namespace std;
class String
{
friendostream& operator<<(ostream& os, const String &other);
public:
String(const char *str = NULL);
String(const String& other);
~String();
String& operator=(const String &other);
private:
char *m_cdata;
};
String::~String()
{
delete[]m_cdata;
}
String::String(const char *str)
{
if (str == nullptr)
{
m_cdata = new char[1];
*m_cdata = '\0';
}
else
{
int length = strlen(str);
m_cdata = new char[length + 1];
strcpy_s(m_cdata,length+1, str);
}
}
String::String(const String& other)
{
int length = strlen(other.m_cdata);
m_cdata = new char[length + 1];
strcpy_s(m_cdata, length+1,other.m_cdata);
}
String& String::operator=(const String &other)
{
//检查自己赋值
if (this == &other)
return *this;
//释放点原有的内存
delete[]m_cdata;
//分配新的内存,并且复制内容
int length = strlen(other.m_cdata);
m_cdata = new char[length + 1];
strcpy_s(m_cdata,length+1, other.m_cdata);
return *this;
}
ostream& operator<<(ostream& out,const String &other)
{
out << other.m_cdata;
return out;
}
int main()
{
String str("hello");
const String str2 = str;
cout << str2 << endl;
system("pause");
return 0;
}
#include<cstring>
using namespace std;
class String
{
friendostream& operator<<(ostream& os, const String &other);
public:
String(const char *str = NULL);
String(const String& other);
~String();
String& operator=(const String &other);
private:
char *m_cdata;
};
String::~String()
{
delete[]m_cdata;
}
String::String(const char *str)
{
if (str == nullptr)
{
m_cdata = new char[1];
*m_cdata = '\0';
}
else
{
int length = strlen(str);
m_cdata = new char[length + 1];
strcpy_s(m_cdata,length+1, str);
}
}
String::String(const String& other)
{
int length = strlen(other.m_cdata);
m_cdata = new char[length + 1];
strcpy_s(m_cdata, length+1,other.m_cdata);
}
String& String::operator=(const String &other)
{
//检查自己赋值
if (this == &other)
return *this;
//释放点原有的内存
delete[]m_cdata;
//分配新的内存,并且复制内容
int length = strlen(other.m_cdata);
m_cdata = new char[length + 1];
strcpy_s(m_cdata,length+1, other.m_cdata);
return *this;
}
ostream& operator<<(ostream& out,const String &other)
{
out << other.m_cdata;
return out;
}
int main()
{
String str("hello");
const String str2 = str;
cout << str2 << endl;
system("pause");
return 0;
}
阅读全文
0 0
- C++面试题:String类的实现
- C++面试题--string类的实现
- C++面试题:String类的实现
- C++面试题:String类的实现
- C++【常见面试题】String类的实现,以及深拷贝、浅拷贝问题
- c string 面试题
- C++:【常见面试题】String类的写法
- String类的实现 -- C++经典面试题
- 【C++】面试题:模拟实现string类(版本一:用深度拷贝来实现 )
- String 的面试题
- String的面试题
- String类面试题
- 面试题 String类
- String类猥琐的面试题
- String类的一道面试题
- C/C++面试题:编写类String的构造函数、析构函数和赋值函数。
- String类型的面试题
- String相关的面试题
- 递归
- 剑指Offer(第二版)面试题30:包含min函数的栈
- mysql SQL设置外键约束ON DELETE CASCADE
- stack overflow[part2]
- 学习笔记
- C++面试题:String类的实现
- JAVA的map集合练习
- Linux下部署Redis
- JDK之SET
- 下拉导航菜单被遮住解决办法
- centos中安裝redis
- sql 语句几种执行方法的比较
- Spring内部bean实例
- JDK8-练习题使用方法引用、构造引用、数组引用改造(五)