Fat*_*imi 0 c++ constructor copy-constructor
我在网上发现了这段代码:
#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)
我不明白为什么在没有作为参数传递给复制构造函数的对象时调用复制构造函数?另外,在调试时,我理解在函数main完成后调用析构函数.为什么它被调用以及为什么它在函数main终止后被调用?谢谢,
void display(Line obj) {
Run Code Online (Sandbox Code Playgroud)
此函数按值获取其参数.这意味着将此参数传递给此函数将复制它.这是调用时main() 调用复制构造函数的地方display().
如果您更改此函数,以便通过引用获取其参数:
void display(Line &obj) {
Run Code Online (Sandbox Code Playgroud)
您将发现不再从示例程序中调用复制构造函数.
您将在C++手册中找到有关按值与参考传递参数的更多信息.