拷贝构造函数

Copy Constructor

本文关键字:构造函数 拷贝      更新时间:2023-10-16

我是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()函数中接收对象作为引用[I]。当display(Line &Obj)]时,它没有调用复制构造函数。

当你按值传递一些东西时,复制构造函数被用来初始化传递的参数——也就是说,传递的是你给出的任何东西的副本,所以复制构造函数当然是用来创建那个副本的。

如果不希望值被复制,则传递一个(可能是const)引用。