设为首页 加入收藏

TOP

关于构造函数、赋值函数和析构函数
2014-11-05 21:45:05 】 浏览:226
Tags:关于 构造 函数

  如果不自己定义构造函数,系统会生成一个默认构造函数;但即使用户自定义了一个构造函数甚至不是默认构造函数,那么系统也不会自动生成一个默认构造函数,所以当需要默认构造函数并且已经自己定义了某些构造函数后,必须自己定义默认构造函数。The default constructor is used whenever we define an object but do not supply an initializer.A constructor that supplies default arguments for all its parameters also defines the default constructor.(c++primer)


  但是拷贝构造函数是例外的,也就是说即使我们自己定义了其他的构造函数,系统自己定义的也还是会存在。但是编译器生成的拷贝构造函数是按“bit”进行的,如果有指针之类的数据成员,那么拷贝后两个对象的指针成员会指向同一个内存区域,这样就会产生一些问题。但是有一个列外就是数组成员,编译器生成的拷贝构造函数会将数组的元素逐一进行拷贝到新定义的对象。所以很多时候需要我们自己定义拷贝构造函数。但是有时候,有些类却不允许进行拷贝构造或者赋值,这时我们可以将拷贝构造的访问控制定义为private的,但是友元仍能使用这些函数,所以为了绝对防止使用拷贝构造,我们在private中只声明不定义就可,从这里也可以推出,如果自己定义或者声明了拷贝构造函数,编译器就不会自动生成。同样赋值操作几乎跟拷贝构造函数一样,编译器也会自动生成赋值操作,并且其工作方式跟拷贝构造函数一样。其实它们是联系在一起的也就是需要其中一个绝大时候就会需要另一个,原因可能是来自语义上的。(自己定义拷贝构造函数和赋值运算后,编译器就不会自动生成了)


  析构函数:(c++ primer) It serves as the complement to the constructors of the class. An object that is dynamically allocated is destroyed only when a pointer pointing to the object is delete.The destructor is not run when a reference or a pointer to an object goes out of scope. The destructor is run only when a pointer to a dynamically allocated object is deleted or when an actual object (not a reference to the object) goes out of scope.


  If a class needs a destructor, it will also need the assignment operator and a copy constructor. This rule is often referred to as the Rule of Three, indicating that if you need a destructor, then you need all three copy-control members. 可能是语义上的要求,具体原因不是很清楚。


  A destructor, in general, can perform any operation that the class designer wishes to have executed subsequent to the last use of an object of that class.


  In particular, the synthesized destructor does not delete the object pointed to by a pointer member.


  与拷贝构造函数与赋值函数不同的是,编译器定义的析构函数是一直存在的,即使是我们定义了自己的析构函数,当对象退出作用范围后,自己定义的析构函数先运行,然后编译器定义的析构函数再运行。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇MFC控件指针公用释放方法 下一篇LineDDA函数使用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目