#include <iostream>
using namespace std;
class String
{
public:
//普通构造函数
String(const char *str = NULL);
//拷贝构造函数
String(const String &other);
//赋值构造函数
String & operator = (const String &other);
//析构函数
~String(void);
//打印数据
void Display();
private:
void IsSuccessMemory()
{
if(NULL == m_data)
{
cout<<"failure! Error,Menory allocation failure!";
exit(0);
}
}
//用于保存字符串
char *m_data;
};
String::String(const char* str)
{
if(NULL == str)
{
m_data = new char[ 1 ];
IsSuccessMemory();
*m_data = '\0';
}
else
{
int length = strlen(str);
m_data = new char [length + sizeof(char)];
IsSuccessMemory();
strcpy(m_data, str);
}
}
String::String(const String &other)
{
int length = strlen(other.m_data);
m_data = new char [ length + sizeof(char)];
IsSuccessMemory();
strcpy(m_data, other.m_data);
}
String & String::operator = (const String &other)
{
if(this == &other)
{
return *this;
}
delete [] m_data;
m_data = NULL;
int length = strlen(other.m_data);
m_data = new char [length + sizeof(char)];
IsSuccessMemory();
strcpy(m_data,other.m_data);
//返回本对象的引用
return *this;
}
String::~String()
{
delete [] m_data;
}
void String::Display()
{
cout<<m_data<<endl;
}
void main()
{
String str("Hello");//普通构造函数
String s2 = str;//拷贝构造函数
s2.Display();
String s3;
s3 = str;//赋值函数
s3.Display();
}class String {
public:
String(const char* str = NULL);
String(const String& other);
String& operator= (const String& other);
~String();
private:
char* m_data;
}
String:String(const char* str) {
if (str == NULL) {
m_data = new (std::nothrow) char[sizeof(char)];
if (m_data == NULL) {
printf("failed to alloc memory of m_data.");
exit(0);
}
*m_data = '\0';
} else {
m_data = new (std::nothrow) char[strlen(str) + sizeof(char)];
if (m_data == NULL) {
printf("failed to alloc memory of m_data.");
exit(0);
}
strcpy(m_data, str);
}
}
String::String(const String& other) {
m_data = new (std::nothrow) char[strlen(other.m_data) + sizeof(char)];
if (m_data == NULL) {
printf("failed to alloc memory of m_data.");
exit(0);
}
strcpy(m_data, other.m_data);
}
String& String::operator=(const String& other) {
if (this == &other) {
return *this;
}
delete []m_data;
m_data = NULL;
m_data = new (std::nothrow) char[strlen(other.m_data) + sizeof(char)];
if (m_data == NULL) {
printf("failed to alloc memory of m_data.");
exit(0);
}
strcpy(m_data, other.m_data);
return *this;
}
String:~String() {
if (m_data == NULL) {
delete []m_data;
m_data = NULL;
}
}

被折叠的 条评论
为什么被折叠?



