C++ 在c+中复制构造函数+;争论不休
为什么此代码在传递的对象不是Line类型且没有等于运算符/显式调用时调用复制构造函数。行a和行a()之间是否有差异。C++ 在c+中复制构造函数+;争论不休,c++,pass-by-reference,copy-constructor,C++,Pass By Reference,Copy Constructor,为什么此代码在传递的对象不是Line类型且没有等于运算符/显式调用时调用复制构造函数。行a和行a()之间是否有差异。 我从许多在线教程中看到它应该是线型的。我是C++的新手。请帮助< /P> #include <iostream> using namespace std; class Line { public: int getLength( void ); Line( int len ); // simple con
我从许多在线教程中看到它应该是线型的。我是C++的新手。请帮助< /P>
#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;
}
#包括
使用名称空间std;
班级线
{
公众:
int getLength(void);
行(int len);//简单构造函数
行(constline&obj);//复制构造函数
~Line();//析构函数
私人:
int*ptr;
};
//成员函数定义,包括构造函数
行::行(int len)
{
cout这是因为您的display
方法按值接受其参数-因此,当您传递参数时,会创建一个副本。为了避免复制,请通过添加一个符号和,将参数声明为对行的引用,而不是对的引用:
void display(Line& obj)
{
cout << "Length of line : " << obj.getLength() <<endl;
}
然后还需要将Line::getLength()
方法声明为const
成员函数,否则编译器将不允许您在const
对象上调用它:
int getLength( void ) const;
通常,在以下情况下会调用副本构造函数:
当类的对象通过值返回时
当类的对象通过值作为参数传递(给函数)时。(这是您的情况)
当一个对象基于同一类的另一个对象构造时,例如A(obj)
当编译器生成临时对象时
“在行a;
和行a();
之间有区别吗?”。
int getLength( void ) const;