用不同的参数复制c ++中的构造函数

Hem*_*thi 2 c++ pass-by-reference copy-constructor

为什么这个代码在传递的对象不是Line类型时调用复制构造函数,并且没有等于operator/explicit调用.A行和A行()之间有区别吗?
我从许多在线教程中读到它应该是Line类型.我是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;
}
Run Code Online (Sandbox Code Playgroud)

atk*_*ins 10

这是因为您的display方法通过值接受其参数- 因此在传递参数时会生成副本.为了避免复制,声明参数是一个参考Line代替,通过添加符号,&:

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

如果您想确保该display方法不会修改您的方法Line,也可以考虑将其作为const参考:

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

然后,您还需要将您的Line::getLength()方法声明为const成员函数,否则编译器将不允许您在const对象上调用它:

int getLength( void ) const;
Run Code Online (Sandbox Code Playgroud)