源碼
// 06CopyConstructor.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream.h"
class Test
{
int i;
int *p;
public:
Test(int ai,int value)
{
i = ai;
p = new int(value);
}
~Test()
{
delete p;
}
Test(const Test& t)
{
this->i = t.i;
this->p = new int(*t.p);
}
};
//思考1. 什麼時候需要寫出拷貝構造
//思考2. 什麼淺拷貝(bitwise Copy),什麼是深拷貝(logical copy)?
int main(int argc, char* argv[])
{
Test t1(1,2);
Test t2(t1);//copy constructor
//思考3. 除了上述直接的拷貝構造調用外,什麼時候還會調用到拷貝構造函數?
return 0;
}
//思考4. 函數參數傳遞是,pass by value 和 pass by address(pointer or reference)有何優劣?
思考1: 什麼時候需要寫出拷貝構造
避免淺拷貝
思考2:什麼淺拷貝(bitwise Copy),什麼是深拷貝(logical copy)?
淺拷貝:對象A和對象B中指針成員變量指向同一個地址,就叫淺拷貝。
深拷貝:對象A和對象B中指針成員變量指向不同的地址,但是兩個地址對應的值是相同的。
思考3:除了上述直接的拷貝構造調用外,什麼時候還會調用到拷貝構造函數?
對象在創建時使用其他的對象初始化時以及對象作爲函數的參數進行值傳遞時
思考4:函數參數傳遞是,pass by value 和 pass by address(pointer or reference)有何優劣?
passby value | passby address |
---|---|
read | read/write |
sizeof(value) | sizeof(int) |
copy-constructor | no mass |