String类定义与部分函数实现

. 已知String类定义如下: 

class String
{
public:
  String(const char 
*str = NULL); // 通用构造函数
  String(const String &another); // 拷贝构造函数
  ~String(); // 析构函数
  String& operater =(const String &rhs); // 赋值函数
private:
  charm_data; // 用于保存字符串
};
 

  

尝试写出类的成员函数实现。

答案:

复制代码
复制代码
String::String(constchar*str)
{
if ( str == NULL ) // strlen在参数为NULL时会抛异常才会有这步判断
{
m_data 
=newchar[1] ;
m_data[
0='\0' ;
}
else
{
m_data 
=newchar[strlen(str) +1];
strcpy(m_data,str);
}

String::String(
const String &another)
{
m_data 
=newchar[strlen(another.m_data) +1];
strcpy(m_data,other.m_data);
}

String
& String::operator=(const String &rhs)
{
if ( this==&rhs)
return*this ;
delete []m_data; 
//删除原来的数据,新开一块内存
m_data =newchar[strlen(rhs.m_data) +1];
strcpy(m_data,rhs.m_data);
return*this ;
}

String::
~String()
{
delete []m_data ;
}
复制代码
复制代码

 

已知strcpy的函数原型char *strcpy(char *strDest, const char *strSrc)其中strDest 是目的字符串,strSrc 是源字符串。不调用C++/C 的字符串库函数,请编写函数 strcpy。

答案:

复制代码
复制代码
/*
编写strcpy函数(10分)
已知strcpy函数的原型是
char *strcpy(char *strDest, const char *strSrc);
其中strDest是目的字符串,strSrc是源字符串。
(1)不调用C++/C的字符串库函数,请编写函数 strcpy
(2)strcpy能把strSrc的内容复制到strDest,为什么还要char * 类型的返回值?
答:为了 实现链式表达式。 // 2分
例如 int length = strlen( strcpy( strDest, “hello world”) );
*/


#include 
<assert.h>
#include 
<stdio.h>
char*strcpy(char*strDest, constchar*strSrc)
{
assert((strDest
!=NULL) && (strSrc !=NULL)); // 2分
char* address = strDest;   // 2分
while( (*strDest++=*strSrc++!='\0' )       // 2分
NULL; 
return address ;    // 2分
}
复制代码
复制代码

 

另外strlen函数如下:

 

复制代码
复制代码
#include<stdio.h>
#include
<assert.h> 
int strlen( constchar*str ) // 输入参数const
{
assert( str 
!= NULL ); // 断言字符串地址非0
int len = 0;
while( (*str++!='\0' ) 

len
++

return len;
}
复制代码
复制代码

 

 

posted on 2013-05-23 11:16  samules  阅读(181)  评论(0编辑  收藏  举报

导航