gpt4 book ai didi

c++ - 使用不同的参数在 C++ 中复制构造函数

转载 作者:太空狗 更新时间:2023-10-29 23:32:39 24 4
gpt4 key购买 nike

当传递的对象不是 Line 类型并且没有等于运算符/显式调用时,为什么这段代码调用复制构造函数。 Line A 和 Line 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;
}

最佳答案

这是因为您的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;

关于c++ - 使用不同的参数在 C++ 中复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33278262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com