1,[C++]编写string类的构造函数,析构函数和拷贝构造函
程序如下所示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
class String{
public:
String(const char*str = NULL);
String(const String &another);
~String();
String& operator =(const String &rhs);
private:
char* m_data;
};
String::String(const char*str)
{
if(str == NULL)
{
m_data = new char[1];
m_data = '\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,another.m_data);
}
String & String::operator=(const String &rhs)
{
if(this ==&rhs)
{
return *this;
}
delete []m_data;
m_data = new char[strlen(rhs.m_data)+1];
strcpy(m_data,rhs.m_data);
return*this;
}
String::~String()
{
delete []m_data;
}
int main()
{
String("hello,welcome");
return 0;
}
总结:new和malloc的区别
1,
malloc与free是C++/C语言的标准库函数,new/delete是C++的运算符。它们都可用于申请动态内存和释放内存。