1. 程式人生 > >類的直接初始化、複製初始化、賦值

類的直接初始化、複製初始化、賦值

一. 定義區別:

     初始化是建立變數時給變數賦初值;賦值是擦除變數之前的值,賦給它新的值。

     類的直接初始化是在建立物件時呼叫類的預設建構函式或普通建構函式;

     類的複製初始化是在建立物件時呼叫類的拷貝建構函式

     類的賦值是呼叫類的賦值操作符。

     對於類class A{};

     class A{

            A();   //預設建構函式

            A(const A& a);  //拷貝建構函式,拷貝建構函式是為了防止淺拷貝,所以對於會發生淺拷貝的類,需要定義拷貝建構函式

           A& operator=(const A& a);   //賦值操作符

           ~A();    //解構函式

     }

二. 可以通過下面程式碼來加深瞭解:

#include<iostream>
#include<vector>
#include<string>
using  namespace std;

class student
{
    
public:
    student()
    {
        cout<<"預設建構函式"<<endl;
    }
    student(const  student&)
    {
        cout<<"拷貝建構函式"<<endl;
        
    }
    student  &operator=(const student &)
    {
        cout<<"賦值操作符"<<endl;
        return *this;
    }
    ~student()
    {
        cout<<"解構函式"<<endl;
    }
};

//形參為student物件
void fun1(student obj)
{
}
//形參為student物件的引用
void fun2(student &obj)
{
}
student fun3()
{
    student  obj;
    return obj;
}



int main()
{
    cout<<"student a"<<endl;
    student a;        //呼叫預設建構函式
    cout<<"fun1(a);"<<endl;
    fun1(a);             //呼叫拷貝建構函式和解構函式
    cout<<"fun2(a);"<<endl;
    fun2(a);        //不呼叫四大函式
    cout<<"a=fun3();"<<endl;
    a=fun3();       //呼叫預設建構函式、賦值操作符、解構函式
    cout<<"student  *p=new student;"<<endl;
    student  *p=new student;    //呼叫預設建構函式
    cout<<"vector<student> even(3);"<<endl;
    vector<student> even(3);     //呼叫三次預設建構函式
    cout<<"delete p"<<endl;
    delete p;              //呼叫解構函式
    cout<<"student b=a;"<<endl;
    student b=a;          //呼叫拷貝建構函式
    cout<<"student c;c=a; "<<endl;
    student c;          //呼叫預設建構函式
    c=a;                //呼叫賦值操作符
    system("pause");
    
    
    
    
    return 0;    //呼叫多次解構函式
}