淺拷貝與深拷貝

2021-10-02 09:33:22 字數 3579 閱讀 1382

public

class

shallowcopy

建立的物件:student

} 拷貝的物件:student

} 修改老師的資訊後:

建立的物件:student

} 拷貝的物件:student}}

class

teacher

implements

cloneable

public string getname()

public

void

setname

(string name)

public

intgetage()

public

void

setage

(int age)

@override

public string tostring()

';}}

class

student

implements

cloneable

public string getname()

public

void

setname

(string name)

public

intgetage()

public

void

setage

(int age)

public teacher getteacher()

public

void

setteacher

(teacher teacher)

/** * 呼叫父類(object)的方法進行拷貝

建立的物件:student

} 拷貝的物件:student

} 修改老師的資訊後:

建立的物件:student

} 拷貝的物件:student}}

class

teacher

implements

cloneable

public

void

setname

(string name)

public

intgetage()

public

void

setage

(int age)

public

teacher

(string name,

int age)

@override

public string tostring()

';}@override

public object clone()

throws clonenotsupportedexception

}class

student

implements

cloneable

public

void

setname

(string name)

public

intgetage()

public

void

setage

(int age)

public teacher getteacher()

public

void

setteacher

(teacher teacher)

public

student

(string name,

int age, teacher teacher)

@override

public string tostring()

';}@override

public object clone()

throws clonenotsupportedexception

}

public

class

deepcopyserializable

建立的物件:student

} 拷貝的物件:student

} 修改老師的資訊後:

建立的物件:student

} 拷貝的物件:student}}

class

teacher

implements

serializable

public

void

setname

(string name)

public

intgetage()

public

void

setage

(int age)

public

teacher

(string name,

int age)

@override

public string tostring()

';}@override

public object clone()

throws clonenotsupportedexception

}class

student

implements

serializable

public

void

setname

(string name)

public

intgetage()

public

void

setage

(int age)

public teacher getteacher()

public

void

setteacher

(teacher teacher)

public

student

(string name,

int age, teacher teacher)

@override

public string tostring()

';}/**

* 通過序列化和反序列化進行拷貝

「淺拷貝」與「深拷貝」

c 中物件的複製就如同 轉殖 用乙個已有的物件快速地複製出多個完全相同的物件。一般而言,以下三種情況都會使用到物件的複製 1 建立乙個新物件,並用另乙個同類的已有物件對新物件進行初始化,例如 cpp view plain copy class rect rect rect1 rect rect2 r...

淺拷貝與深拷貝

淺拷貝 1 2 myclass a,b a b 為了封裝性和解耦,同型別的兩個物件之間進行賦值操作時,所有成員變數被複製,包括私有成員 指標變數。類的成員函式在傳遞或返回物件時都會進行物件複製產生臨時物件,比如函式呼叫時實參變為形參,以及函式返回物件。考慮到效能和使用者要求不同,編譯器不複製物件內部...

「淺拷貝」與「深拷貝」

c 中物件的複製就如同 轉殖 用乙個已有的物件快速地複製出多個完全相同的物件。一般而言,以下三種情況都會使用到物件的複製 1 建立乙個新物件,並用另乙個同類的已有物件對新物件進行初始化,例如 cpp view plain copy class rect rect rect1 rect rect2 r...