强调一下几个重点:
(1)new 操作符申请内存失败,是抛出异常,并不是返回NULL,若想申请失败返回NULL,需要加 (std::nothrow);
(2)使用std::nothrow 需要加头文件 #include<new>
(3)使用assert
(4)构造函数有参数时最好加默认参数,这样就有默认构造函数了,且不要忘了定义为const
(5)赋值操作符函数体if语句中的条件必须是 this != &other,为什么if(*this != other)不行????
刚想了下原因是:定义的类型没有!=操作符啊,怎么可以比较呢,只能比较指针了。。。
#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<iostream>
#include<new>
using namespace std;
class String
{
private:
char *m_data;
public:
String(const char *str = NULL);
~String();
char * get_m_data() {return m_data;}
String(const String&);
String& operator= (const String &);
};
String::String(const char *str)
{
if(str == NULL)
{
m_data = new (std::nothrow) char[1];
assert(m_data != NULL);
*m_data = '\0';
}else
{
m_data = new (std::nothrow) char[strlen(str) + 1];
assert(m_data != NULL);
strcpy(m_data, str);
}
}
String::~String()
{
if(m_data != NULL)
{
delete []m_data;
m_data = NULL;
}
}
String::String(const String &other)
{
m_data = new (std::nothrow) char[strlen(other.m_data) + 1];
assert(m_data != NULL);
strcpy(m_data, other.m_data);
}
String& String::operator= (const String &other)
{
if(this != &other)
{
String tmp(other);
char *str = tmp.m_data;
tmp.m_data = m_data;
m_data = str;
}
return *this;
}
int main()
{
String s1("a big brother is watching you!!!");
String s2(s1);
//printf("haha\n");
String s3;
s3 = s1;
printf("%s\n", s1.get_m_data());
printf("%s\n", s2.get_m_data());
printf("%s\n", s3.get_m_data());
return 0;
}