« | September 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | 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 | 30 | | | | | |
|
公告 |
My blog is about my major : network security.the most papers are talk about it ,I like my major ,i wish you could find what's you need in it. |
统计 |
blog名称:我的IT人生 日志总数:78 评论数量:185 留言数量:-1 访问次数:525662 建立时间:2006年4月5日 |
| 
|
本站首页 管理页面 写新日志 退出
[C/C++]编写类string的构造函数、拷贝构造函数和析构函数 |
String 类的原型如下
class String{ public: String(const char *str=NULL); //构造函数 String(const String &other); //拷贝构造函数 ~String(void); //析构函数 String& operator=(const String &other); //等号操作符重载
ShowString();
private: char *m_data; //指针};
String::~String(){ delete [] m_data; //析构函数,释放地址空间}String::String(const char *str){ if (str==NULL)//当初始化串不存在的时候,为m_data申请一个空间存放'\0'; { m_data=new char[1]; *m_data='\0'; } else//当初始化串存在的时候,为m_data申请同样大小的空间存放该串; { int length=strlen(str); m_data=new char[length+1]; strcpy(m_data,str); }}
String::String(const String &other)//拷贝构造函数,功能与构造函数类似。{ int length=strlen(other.m_data); m_data=new [length+1]; strcpy(m_data,other.m_data);}String& String::operator =(const String &other) { if (this==&other)//当地址相同时,直接返回; return *this; delete [] m_data;//当地址不相同时,删除原来申请的空间,重新开始构造;
int length=sizeof(other.m_data); m_data=new [length+1]; strcpy(m_data,other.m_data);
return *this; }
String::ShowString()//由于m_data是私有成员,对象只能通过public成员函数来访问;
{
cout<<this->m_data<<endl;
}
main(){String AD;char * p="ABCDE";String B(p);AD.ShowString();AD=B;AD.ShowString();
}
|
阅读全文(13504) | 回复(2) | 编辑 | 精华 |
回复:编写类string的构造函数、拷贝构造函数和析构函数 |
dupengjx(游客)发表评论于2009/7/11 22:28:45 | 加上#include<string.h>;并把 m_data=new [length+1]; 改为 m_data=new char[length+1];
|
个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除 |
回复:编写类string的构造函数、拷贝构造函数和析构函数 |
276634702(QQ)(游客)发表评论于2008/10/22 11:14:11 | 你这个程序是在哪个软件环境测试的,我在VC下测试不能通过.总是在
String::String(const String &other)//拷贝构造函数,功能与构造函数类似。{ int length=strlen(other.m_data); m_data=new [length+1]; strcpy(m_data,other.m_data);}
报如下错误error C2143: syntax error : missing ';' before '}'
|
个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除 |
» 1 »
|