我是C++的新手,我不明白为什么在下面的代码中调用了复制构造函数:
#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;
}
Run Code Online (Sandbox Code Playgroud)
当它运行时:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Run Code Online (Sandbox Code Playgroud)
为什么在第一个具有简单构造函数的对象之后构造另一个Line对象?
谢谢!
因为你传递的Line是价值
void display(Line obj)
{
cout << "Length of line : " << obj.getLength() <<endl;
}
Run Code Online (Sandbox Code Playgroud)
你应该将它作为常量引用传递,这更快(并且display应该是一个常量方法,因此常量对象可以调用它).
void display(const Line &obj) const
{
cout << "Length of line : " << obj.getLength() <<endl;
}
Run Code Online (Sandbox Code Playgroud)
(如果你换到int getLength( void ) const;)
在您的情况下,考虑重新定义赋值运算符
Line &operator=(const Line &other);
Run Code Online (Sandbox Code Playgroud)
或影响另一行中的一行将复制指针数据,并将在第二个对象删除时崩溃,因为内存将被释放两次.
如果要确保无法调用默认的复制构造函数/赋值运算符,只需在私有部分中声明它们:
private:
Line &operator=(const Line &other);
Line(const Line &other);
Run Code Online (Sandbox Code Playgroud)
试图使用它们的代码将无法编译.