【发布时间】:2021-09-23 08:30:58
【问题描述】:
这是我的代码:
#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 line1(10);
Line line2 = line1; // This also calls copy constructor
display(line1);
display(line2);
return 0;
}
谁能解释一下这个输出?
我无法理解重复打印。
输出:
//Normal constructor allocating ptr
//Copy constructor allocating ptr.
//Copy constructor allocating ptr.
//Length of line : 10
//Freeing memory!
//Copy constructor allocating ptr.
//Length of line : 10
//Freeing memory!
//Freeing memory!
//Freeing memory!
【问题讨论】:
-
我们已经从您之前的两个问题中删除了 C 标记,现在我们正在从这个问题中删除它。我们不是为了好玩。不要使用不相关的标签。您的代码显然不是 C。
-
代码也很奇怪。当你有一个类时,为什么要使用数组来存储数据和元数据?没有意义。
-
另外,您还没有解释不清楚的地方。有哪些细节不清楚?