C++ 复制构造函数
我是C++ 复制构造函数,c++,copy-constructor,C++,Copy Constructor,我是C++编程新手,当我读到一篇关于复制构造函数的C++时,我有一个疑问。当我们将类的对象作为传递值传递给外部函数时,为什么复制构造函数会调用。请按照下面的代码检查我的代码 #include "stdafx.h" #include <iostream> #include <conio.h> using namespace std; class Line { public: int getLength( void ); Line( int
C++编程新手
,当我读到一篇关于复制构造函数的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;
}
#包括“stdafx.h”
#包括
#包括
使用名称空间std;
班级线
{
公众:
int getLength(void);
行(int len);//简单构造函数
行(constline&obj);//复制构造函数
~Line();//析构函数
私人:
int*ptr;
};
//成员函数定义,包括构造函数
行::行(int len)
{
cout当您通过值传递某个内容时,复制构造函数用于初始化传递的参数——即,传递的是您给定的任何内容的副本,因此当然,复制构造函数用于创建该副本
如果不希望复制该值,请改为传递(可能是常量)引用