----------------------------------------------------------------------------------------------------------------------------------------------- 本文提示:《C/C++ 笔试、面试题目大汇总(9)》是本站编辑们为广大网友精选的实用文章,本文阐述了关于文章的相关理论,相对来说专业性强,但是本文只是针对于某个问题提出的见解与论述,未必能辐射到相关问题的方方面面,所以本文处理问题的方法仅仅为您提供一些参考。更多问题请查阅学习中国网其他栏目哦. -----------------------------------------------------------------------------------------------------------------------------------------------
String & operater =(const String &rhs); // 赋值函数
private:
char *m_data; // 用于保存字符串
};
尝试写出类的成员函数实现。
答案:
String::String(const char *str)
{
if ( str == NULL ) //strlen在参数为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 &another)
{
m_data = new char[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; //删除原来的数据,新开一块内存
本文章更多内容:<<上一页 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20 - 21 - 22 - 23 - 24 - 25 - 26 - 27 - 28 - 29 - 下一页>> |