c++ 第四章 第五章:堆与拷贝构造函数

2016-11-10  本文已影响0人  ie大博

第四章

代码啥的没有,主要就是讲述一个思想吧,就是要把问题分析,拆分出类,让主函数调用的方便,老师的意思是说要把函数做成具有面向对象的思想的函数,比较直观易懂。(⊙o⊙)…

第五章:堆与拷贝构造函数

c++里面的“malloc”“free”

public:
    test(int a)
    {
        cout<<"test construct"<<endl;
    }
    ~test()
    {
        cout<<"======"<<endl;
    }
};
int main()
{
    test *t=new test(5);//在堆上建造空间,不用malloc,这个位置给构造函数传参
    cout<<"主函数"<<endl;
    delete t;//释放空间
    return 0;
}

数组在堆上的建造和释放

class test
{
public:
    test()
    {
        cout<<"test construct"<<endl;//这个地方会被执行五次
    }
    ~test()
    {
        cout<<"======"<<endl;//这个地方会被执行五次

    }
};
int main()
{
    test *t=new test[5];//在对上建立一个数组
    cout<<"主函数"<<endl;
    delete[] t;//释放空间,这里面的“【】”不能省略,因为释放的是数组空间
    return 0;
}

构造函数的拷贝

class test
{
    int m_a;
public:
    test(int a)//构造函数只能出现一次
    {
        m_a=a;
        cout<<"test construct"<<m_a<<endl;  }
    ~test()
    {
        cout<<"======"<<m_a<<endl;
    }
    void show()
    {
        cout<<"m_a="<<m_a<<endl;
    }
};
void hello(test temp)
{
    temp.show();
}
int main()
{
    test t1(10);
    t1.show();//调用一次

    hello(t1);//同过hello函数调用一次
        return 0;
}

系统给的拷贝的原理

class test
{
    int m_a;
public:
    test(int a)
    {
        m_a=a;
        cout<<"test construct"<<m_a<<endl;  }
    ~test()
    {
        cout<<"======"<<m_a<<endl;
    }
    void show()
    {
        cout<<"m_a="<<m_a<<endl;
    }
    test(const test& q)///这里传的表示test q,因为
    {
        m_a=q.m_a;
    }
};
void hello(test temp)
{
    temp.show();
}
int main()
{
    test t1(10);
    t1.show();

    hello(t1);
        return 0;
}

当传指针的时候,系统给的构造函数的拷贝会出问题,因为少了指针的初始化,然而delete却没少

using namespace std;
class test
{
    int *m_a;//变量是指针
public:
    test(int a)
    {
        m_a=new int;//分配堆空间
        *m_a=a;
        cout<<"alex is "<<*m_a<<endl;
    }
    ~test()
    {
        cout<<"~test"<<*m_a<<endl;
        delete m_a;//回收空间
    }
    void show()
    {
        cout<<"m_a="<<*m_a<<endl;
    }
    test(const test&q)//注意传参;
    {
        m_a=new int;//因为拷贝的时候两个指针指向一块空间,然而却释放两次堆空间,
然后这里面需要新建一个堆空间;
        *m_a=*q.m_a;
    }
};
int main()
{

    test t1(10);
    t1.show();
    test t2(t1);
    t2.show();
}
上一篇 下一篇

猜你喜欢

热点阅读