【发布时间】:2020-12-20 06:23:51
【问题描述】:
我有以下行为奇怪的代码。目前我理解的流程是,display(line); 会调用复制构造函数Line::Line(const Line &obj),并传入line 的引用。但是cout<<"[origin] *ptr="<<*obj.ptr<<endl; 将打印[origin] *ptr=32767 而不是[origin] *ptr=10。
更奇怪的是,如果我取消注释// int x=3;,它会正确打印,但我真的不知道为什么。
您可以在以下位置找到可执行代码:https://www.onlinegdb.com/pjbPO0X1f
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len );
Line( const Line &obj);
private:
int *ptr;
};
// constructor
Line::Line(int len)
{
ptr=&len;
cout<<"*ptr="<<(*ptr)<<endl;
}
// copy constructor
Line::Line(const Line &obj)
{
// int x=3;
cout<<"[origin] *ptr="<<*obj.ptr<<endl;
ptr = new int;
*ptr = *obj.ptr; // copy
}
int Line::getLength( void )
{
return *ptr;
}
void display(Line obj)
{
cout << "line=" << obj.getLength() <<endl;
}
int main( )
{
Line line(10);
display(line);
return 0;
}
【问题讨论】:
-
简单的评论是——不要这样写 C++ 代码。为什么在不需要的时候引入指针?
标签: c++ copy-constructor