现在很多面试题都是要求写一个String类,主要检查Big 3,也就是主要检查构造函数,析构函数和赋值函数.(不要告诉我你以为是:姚明,麦蒂,阿泰...),这也是很考验基本功的一个题目.我今天自己写了一个MyString类,顺便加上了StrAdd函数用于字符串相加,Get函数用于输出.详细代码如下,说明见注释.
- #include<iostream>
- #include "assert.h"
- using namespace std;
- // MyString类声明
- class MyString
- {
- public:
- MyString(const char* str=NULL);
- ~MyString();
- MyString(const MyString & str);
- MyString &operator=(const MyString & str);
- MyString &StrAdd(
- const MyString &str1,const MyString &str2);
- char* Get();
- private:
- char* m_data;
- };
- // 构造函数
- MyString::MyString(const char* str/* =NULL */)
- {
- // 空的就给个结束0就ok了
- if (NULL==str)
- {
- m_data=new char[1];
- m_data[0]='\0';
- }
- else
- {
- // 根据str创建新的m_data..记得加1哦...
- m_data=new char[strlen(str)+1];
- strcpy(m_data,str);
- }
- }
- // 析构函数
- MyString::~MyString()
- {
- // 可以不用[] 因为是内部的
- delete []m_data;
- }
- // 拷贝构造函数
- MyString::MyString(const MyString & str)
- {
- // 根据str.m_data创建长度...记得加1哦...
- m_data=new char[strlen(str.m_data)+1];
- strcpy(m_data,str.m_data);
- }
- // 赋值函数
- MyString &MyString::operator=(const MyString & str)
- {
- // 检查不是自己给自己赋值的才构建...否则直接返回了...
- if (&str!=this) // 注意:不要写成str!=*this 这样是挂了的...
- {
- // only 一次机会...不要内存泄露了哦...
- delete [] m_data;
- // new一个...创建空间
- m_data=new char[strlen(str.m_data)+1];
- strcpy(m_data,str.m_data);
- }
- // 实现链式操作...
- return *this;
- }
- // 相加函数
- MyString &MyString::StrAdd(
- const MyString &str1,const MyString &str2)
- {
- assert((&str1!=NULL) && (&str2!=NULL));
- delete []m_data;
- m_data=new char[strlen(str1.m_data)+strlen(str2.m_data)+1];
- strcpy(m_data,str1.m_data);
- strcat(m_data,str2.m_data);
- return *this;
- }
- // 获得字符串函数
- char* MyString::Get()
- {
- return m_data;
- }
- void main(void)
- {
- // a-f中只有c是利用拷贝构造函数初始化,其余利用一般构造函数
- // d=b是让d使用赋值函数
- // f为了表示利用了链式操作,e表示利用StrAdd
- MyString a("hello,"); // 一般构造函数初始化
- MyString b("world!"); // 一般构造函数初始化
- MyString c(a); // 拷贝构造函数初始化
- MyString d,e,f; // 一般拷贝构造函数初始化,m_data仅仅有个'\0'
- d=b; // 赋值函数对d赋值,来自b.m_data
- f.StrAdd(e.StrAdd(a,b),e); // 利用StrAdd进行链式操作,并相加
- // 下面均使用Get()进行输出
- cout<<"a="<<a.Get()<<endl;
- cout<<"b="<<b.Get()<<endl;
- cout<<"c="<<c.Get()<<endl;
- cout<<"d="<<d.Get()<<endl;
- cout<<"e="<<e.Get()<<endl;
- cout<<"f="<<f.Get()<<endl;
- system("pause");
- }