2015-10-22 53 views
2

为什么这个代码在传递的对象不是Line类型并且没有等于操作符/显式调用时调用拷贝构造函数。线A和线A()之间有区别。
我从网上很多教程,它应该是线路type.I的阅读是一个新手,C++请帮忙使用不同的参数在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; 
    *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; 
} 
+0

_“Line A;'和'Line A();'?”_ [Yes]是否有区别(https://en.wikipedia.org/wiki/Most_vexing_parse)。 – nwp

回答

10

这是因为你的display方法,通过价值接受它的参数- 作为结果的副本是当你通过论证时做出的。为了避免副本,声明参数是一个参考Line,而不是通过增加一个符号,&

void display(Line& obj) 
{ 
    cout << "Length of line : " << obj.getLength() <<endl; 
} 

如果你想确保display方法不会修改Line,也可考虑将其const参考:

void display(const Line& obj) 
{ 
    cout << "Length of line : " << obj.getLength() <<endl; 
} 

那么你还需要声明的Line::getLength()方法是const成员函数,否则编译器将不允许ÿ欧调用它const对象:

int getLength(void) const; 
+0

_/_ _(上帝)。谢谢你。 –

2

一般拷贝构造函数将在下列情况下,被称为:

  1. 当一个类的对象是按值返回。
  2. 当该类的一个对象被作为参数的值传递给一个函数时。 这是你的情况
  3. 当一个对象是基于同一类的另一个对象构造的。例如A(obj)
  4. 编译器生成临时对象时。