【发布时间】:2018-10-17 14:33:15
【问题描述】:
我有这个代码。我对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;
cout<<&obj<<endl;
*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() {
int a = 10;
cout<<&a<<endl;
Line line(a);
display(line);
return 0;
}
- 这里我看不出我们在哪里称复制构造器。
- 析构函数被调用了两次。第二个对象在哪里创建?
-
Line::Line(const Line &obj)接收a的地址作为参数?我猜不会。但为什么?a本身不是 Line 的实例,那么为什么函数会接受呢? -
Line::Line(const Line &obj)和Line::Line(const Line obj)之间有什么区别 - 请您解释一下
*ptr = *obj.ptr;。从这里我只知道lhs,它取消引用ptr(又名设置对象的值)。但我没有得到 rhs 中的内容?
为了清楚起见,如果您用更少的技术术语和更多的例子来解释,我将不胜感激
上面的代码输出如下:
0x7fff692196a4
Normal constructor allocating ptr
Copy constructor allocating ptr.
0x7fff69219698
Length of line : 10
Freeing memory!
Freeing memory!
【问题讨论】:
-
那么这个程序的输出是什么?如果此处未实现默认构造函数,您是如何发现它被调用的?为
linemain函数局部变量和objdisplay函数参数调用析构函数(这是复制构造的)。 -
您没有默认构造函数。你在说
Line(int)吗? -
是的,对不起。编辑
-
@Yura 你知道什么是传值吗?
-
@melpomene 我觉得所有问题都源于他们不知道按值传递会导致复制。
标签: c++