2013-03-06 143 views
3

我是C++ programming的新手,我在閱讀關於複製構造函數的C++時遇到了疑問。爲什麼複製構造函數會在我們將類的對象傳遞給外部函數時傳遞值作爲值傳遞。請通過我的代碼如下。複製構造函數

#include "stdafx.h" 
#include <iostream> 
#include <conio.h> 
using namespace std; 

class Line 
{ 
    public: 
     int getLength(void); 
     Line(int len);    // simple constructor 
     Line(const Line &obj);  // copy constructor 
     ~Line();      // destructor 

    private: 
     int *ptr; 
}; 

// Member functions definitions including constructor 
Line::Line(int len) 
{ 
    cout << "Normal constructor allocating ptr" << endl; 
    ptr = new int; 
    *ptr = len; 
} 

Line::Line(const Line &obj) 
{ 
    cout << "Copy constructor allocating ptr." << endl; 
    ptr = new int; 
    *ptr = *obj.ptr; // copy the value 
} 

Line::~Line(void) 
{ 
    cout << "Freeing memory!" << endl; 
    delete ptr; 
} 

int Line::getLength(void) 
{ 
    return *ptr; 
} 

void display(Line obj)//here function receiving object as pass by value 
{ 
    cout << "Length of line : " << obj.getLength() <<endl; 
} 

// Main function for the program 
int main() 
{ 
    Line line(10); 
    display(line);//here i am calling outside function 
    _getch(); 
    return 0; 
} 

在上面我將傳遞類的對象作爲參數和顯示函數接收它作爲值傳遞。我的疑問是,當我將對象傳遞給不是類的成員的函數時,爲什麼複製構造函數正在調用。如果我在display()函數[即顯示(行&Obj)]收到對象作爲參考,它不調用複製構造函數。請幫助我有什麼區別。

回答

10

當您通過值傳遞某些東西時,複製構造函數用於初始化傳遞的參數 - 即傳遞的是您給出的任何副本,所以當然使用複製構造函數創建該副本。

如果您不想複製該值,請傳遞(可能是const)引用。