C++类和对象,6个基本函数

这篇博客探讨了C++中动态内存管理的方法,包括使用new和delete操作符,以及深拷贝和浅拷贝的概念。文章通过String类的实现展示了如何正确处理对象拷贝和赋值操作,确保内存的正确分配和释放。同时,提到了C语言中的内存管理函数malloc、calloc和realloc,并对比了C++中的内存管理方式。
摘要由CSDN通过智能技术生成

//采用&返回的时候要注意返回的对象受不受影响
#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;
    
    };
    
    
    */
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值