我有这个代码。我不是那么精通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!