深拷貝(自己寫拷貝構造函數),淺拷貝(默認的拷貝構造函數)

#include <iostream>
#include <string>

using namespace std;

class student
{
private:
        char *m_name;
        int m_age;
public:
        //構造函數(如果不寫構造函數,系統會調用默認構造函數)    
        student(char *name,int age)                
        {
            m_age = age;
            m_name = new char[20];            //C++申請內存空間
            // m_name = (char *)malloc(sizeof(char)*100);//C語言申請內存空間
            strcpy(m_name,name);
        }
        
        student(const student &p)                //拷貝構造函數
        {
            cout<<"-----copy-----"<<endl;
            m_age = p.m_age;
            m_name = new char[20];
            // m_name = (char *)malloc(sizeof(char)*100);
            strcpy(m_name,p.m_name);
        }
        
        ~student()                                //析構函數
        {
            m_age = 0;
            if(m_name != NULL)
            {
                // free(m_name);            //C語言釋放內存空間
                delete[]m_name;            //C++釋放內存空間
                m_name = NULL;
            }
        }
        
        void print()
        {
            cout<<"name :"<<m_name<<'\t'<<"age:"<<m_age<<endl;
        }
};

int main()
{
    student stu1("gg",13);            //調用構造函數
    stu1.print();
    
    student stu2(stu1);                //深拷貝,調用自己寫的拷貝構造函數
    stu2.print();
    
    
    return 0;
}
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章