您的位置:首页 > 其它

类String的 构造函数、拷贝构造函数、析构函数、赋值函数实现

2010-11-02 15:55 387 查看
#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<algorithm>
#include<time.h>
#include<cmath>
#include<iomanip>
#include<stdlib.h>
#include<queue>
#include<vector>
using namespace std;
class String
{
public:
String(const char * str=NULL);
String(const String& other);
~String();
String& operator =(const String& other);

char * m_data;
};

String::String(const char *str )
{
if(str==NULL){
m_data=new char[1];
m_data[0]='/0';
}
else{
int len=strlen(str);
m_data=new char[len+1];
strcpy(m_data,str);
}
}
String::String(const String &other)
{
int len=strlen(other.m_data);
m_data=new char[len+1];
strcpy(m_data, other.m_data);
}
String::~String()
{
delete[] m_data;
}
String& String::operator =(const String& other)
{
if(this==&other)	return *this;

delete[] m_data;
int len=strlen(other.m_data);
m_data=new char[len+1];
strcpy(m_data,other.m_data);

return *this;
}

int main()
{
String s1("Jason");
cout<<s1.m_data<<endl;

String s2=s1;
cout<<s2.m_data<<endl;
String s3(s1);
cout<<s3.m_data<<endl;

String s4;
s4=s1;
cout<<s4.m_data<<endl;

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐