//采用&返回的时候要注意返回的对象受不受影响
#include <iostream>
#include"assert.h"
#include <string.h>
using namespace std;
class String
{
public:
String(const char* str = "")
{
//申请字符数组
m_data = new char(strlen(str)+1);
strcpy(m_data, str);
}
String(const String& s)
{
m_data = new char(strlen(s.m_data)+1);
strcpy(m_data, s.m_data);
}
String& operator=(const String& s)
{
if (this != &s)
{
free(m_data);
m_data = new char[strlen(str) + 1];
strcpy(m_data, s.m_data);
}
return*this;
}
~String()
{
delete[]m_data;
m_data = nullptr;
}
private:
char *m_data;
};
/*class Test {
public:
Test()
{
cout << "Test::Test()" << endl;
}
~Test()
{
cout << "Test::~Test()" << endl;
}
private:
int m_date;
};
void main()
{
//Test* pt = (Test * )malloc(sizeof(Test));
//free(pt);
Test* pt = new Test;//new的功能,1.申请空间2。调用构造函数
delete pt;//1.调用析构函数2.释放空间
Test* pt1 = new Test[10];
delete []pt1;
}
*/
/*class Test {
public:
String_rep(const char*str="")
{
m_data = (char*)malloc(strlen(str) + 1);
assert(m_data != NULL);
strcpy(m_data, str)
}
String_rep(const String_rep& rep);
String_rep& operator=(const String_rep& rep);
~String_rep();
private:
char* m_data;
int use_count;
c语言申请空间的方式:malloc,calloc,realloc
malloc和calloc的作用都是开辟空间,区别:malloc不会初始化,calloc会初始化为0
int* ptr = (int*)malloc(sizeof(int) * 10);
assert(ptr != NULL);
free(ptr);
int* ptrl = (int*)calloc(10, sizeof(int));
assert(ptrl != NULL);
free(ptrl);
//realloc();
在C++中的内存管理方式:
通过new和delete操作符进行动态内存管理
int *ptr=new int; //申请的空间为1个空间
delete ptr;
int*ptr=new int(10);//初始化该值为10
delete ptr;
int*ptr2=new int[10];//申请的是数组,申请了10个整型空间
delete []ptr2;
};
*/