拷贝构造函数
Copy Constructor
我是C++ programming
的新手,当我阅读关于复制构造函数的C++
时,我有一个疑问。为什么将类的对象作为按值传递方式传递给外部函数时会调用复制构造函数。
#include "stdafx.h"
#include <iostream>
#include <conio.h>
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;
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)//here function receiving object as pass by value
{
cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main( )
{
Line line(10);
display(line);//here i am calling outside function
_getch();
return 0;
}
在上面我传递类的对象作为参数和显示函数接收它作为传递值。我的疑问是,当我传递对象给一个函数,这不是类的成员为什么复制构造函数调用。如果我在display()
函数中接收对象作为引用[I]。当display(Line &Obj)]时,它没有调用复制构造函数。
当你按值传递一些东西时,复制构造函数被用来初始化传递的参数——也就是说,传递的是你给出的任何东西的副本,所以复制构造函数当然是用来创建那个副本的。
如果不希望值被复制,则传递一个(可能是const)引用。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 与浅拷贝构造函数和深拷贝构造函数混淆
- 使用复制构造函数修复浅拷贝
- 在构造函数中浅拷贝字符串数组
- 如何将深拷贝构造函数实现到链表中?
- C++ 如何为地图创建浅拷贝构造函数
- 如何在允许拷贝限制的同时禁用隐式构造函数转换
- 如何实现拷贝交换习惯用法的复制构造函数
- 拷贝构造函数继承
- 静态内存分配中的浅拷贝构造函数问题
- 拷贝构造函数
- 拷贝构造函数