String实现主要函数

来源:互联网 发布:360跑分软件 编辑:程序博客网 时间:2024/05/29 03:41

#include <iostream>

#include <string>

#include <string.h>

using namespace std;

class CString

{

public:CString(const char *_pStr );

~CString();CString(CString &);

CString &operator= (const CString &);

private:char *m_pStr;

friend ostream & operator<< (ostream & os , const CString & _Str)

{

os << _Str.m_pStr ;

return os;

}

friend istream & operator>>(istream & is , CString & _Str)

{

is >> _Str;

return is;

}

};

 

 

CString::CString(const char *_pStr = NULL)

{

if(NULL == _pStr){m_pStr = new char[1];

m_pStr[0] = '/0';

}

else

{

m_pStr = new char[strlen(_pStr)+1];

strcpy(m_pStr , _pStr);

m_pStr[strlen(_pStr)] = '/0';

}

}

CString::~CString()

{

delete [] m_pStr;m_pStr = NULL;

}


CString::CString(CString & _Str)

{

m_pStr = new char[strlen(_Str.m_pStr)+1];

strcpy(m_pStr,_Str.m_pStr);

m_pStr[strlen(_Str.m_pStr)] = '/0';

}

 

 

operator要小心自我复制的时候正确性

CString& CString::operator= (const CString & _Str)

{

if(_str == *this)

return *this;

m_pStr = new char[strlen(_Str.m_pStr)+1];

strcpy(m_pStr,_Str.m_pStr);

m_pStr[strlen(_Str.m_pStr)] = '/0';

return *this;

}

int main(int argc ,char **argv)

{

CString myString("123");

cout << "first:" << myString;

CString SecString(myString);

cout << endl << SecString;

CString ThirdStr;

ThirdStr = myString;

cout << endl << ThirdStr;

}

 

 

这个面试题有几个需要主义的语法错误

 

1 类定义大括号后面的分号

2  函数声明时候不能有默认行参

3  友元函数需要在类内部定义并且实现

4  默认构造函数也可能是默认形参的构造函数。  也可能有形参。

5  operator = 返回的是*this

6 注意在operator= 的时候直接用 传进来的形参对象的私有成员,这说明 私有成员的访问权限是针对于类定义

的 跟对象没关系。

原创粉丝点击