//
// main.cpp
// 拷貝構(gòu)造函數(shù)
//
// Created by Eric on 16/7/20.
// Copyright ? 2016年 Eric. All rights reserved.
//
#include <iostream>
using namespace std;
/**
* 3.拷貝構(gòu)造函數(shù)調(diào)用的三種形式
3.1.一個(gè)對(duì)象作為函數(shù)參數(shù)铸豁,以值傳遞的方式傳入函數(shù)體麻削;
3.2.一個(gè)對(duì)象作為函數(shù)返回值割择,以值傳遞的方式從函數(shù)返回块攒;
3.3.一個(gè)對(duì)象用于給另外一個(gè)對(duì)象進(jìn)行初始化(常稱為復(fù)制初始化)耸彪。
*/
/**
* 當(dāng)產(chǎn)生新對(duì)象碌上,用已有對(duì)象去初始化新對(duì)象時(shí)才會(huì)調(diào)用拷貝構(gòu)造函數(shù)
*/
class Location
{
public:
/**
* 含參構(gòu)造函數(shù)
*/
Location(int x = 0,int y = 0){
_x = x;
_y = y;
_myP = (char *)malloc(100);
strcpy(_myP, "adfadaf");
cout<<"Constructor Object.\n";
}
Location(const Location &obj){
cout<<"調(diào)用拷貝構(gòu)造函數(shù) \n";
}
/**
* 析構(gòu)函數(shù)
*/
~Location(){
cout<<_x<<","<<"Object destroryed"<<endl;
if (_myP != NULL) {
free(_myP);
}
}
int getX(){
return _x;
}
private:
int _x,_y;
char *_myP;
};
class A{
A(int a){
_a = a;
};
private:
int _a;
};
Location createLocation(){
Location L(10,20);
printf("---->%p\n",&L);
return L;
}
void testFunction(){
createLocation();
}
void testFunction2(){
Location a = createLocation();
printf("---->%p\n",&a);
printf("對(duì)象被扶正:m:%d\n",a.getX());
}
void testFunction3(){
Location B(5,2);
//
Location C = B;
printf("C:m:%d\n",C.getX());
}
void testFunction4(){
Location B(5,2);
//
Location C(19,20);
C = B;
printf("C:m:%d\n",C.getX());
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
// testFunction();
// testFunction2();
// testFunction3();//內(nèi)存泄露 顯示的調(diào)用了內(nèi)存拷貝函數(shù)
testFunction4();//內(nèi)存泄露 隱式的調(diào)用了內(nèi)存拷貝函數(shù)
//
// Location D;
//
// D = B;
return 0;
}
關(guān)鍵總結(jié):
當(dāng)產(chǎn)生新對(duì)象掀鹅,用已有對(duì)象去初始化新對(duì)象時(shí)才會(huì)調(diào)用拷貝構(gòu)造函數(shù)