本文介绍了在创建复制构造函数时,为什么我们通过&的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hi EveryBody,
任何人都可以在创建复制构造函数时解释为什么我们传递& ,为什么不重视任何人可以解释这个?
例如:
Hi EveryBody,
Can anyone can explain , while creating the copy constructor , why we are passing & ,why not value any one can explain about this?
Example:
#include <iostream>
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;
// allocate memory for the pointer;
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)
{
cout << "Length of line : " << obj.getLength() << endl;
}
// Main function for the program
int main( )
{
Line line(10);
display(line);
return 0;
}
问候,
Ranjith
Regards,
Ranjith
推荐答案
这篇关于在创建复制构造函数时,为什么我们通过&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!