一、定义和意义
由己存在的对象,创建新对象。也就是说新对象,不由构造器来构造,而是由拷贝构造器来完成。拷贝构造器的格式是固定的。
class 类名
{
类名( const 类名 & another)
拷贝构造体
}
class A
{
A ( const A & another)
{ }
}
二、规则
与类同名 参数为本类对象的const引用 如无定义,系统提供等位拷贝的函数。一经定义,系统不在提供 系统提供默认的拷贝构造器。一经实现,不复存在 系统提供的时等位拷贝,也就是所谓的浅浅的拷贝 要实现深拷贝,必须要自定义
三、拷贝时机
制作对象的副本 以对象作为参数和返回值
四、浅拷贝和深拷贝的区别
浅拷贝: 即等位拷贝,默认不实现就是浅拷贝,如果原对象本身是有new一块地址的,浅拷贝只是将地址完整的进行拷贝,可能会出现重复析构,释放同一块buf深拷贝: 不仅仅是地址的拷贝, 而是重新申请一块buf,指向新的地址如果类中包含的数据元素全部在栈上,浅拷贝也可以满足需求的。但如果堆上的数据,则会发生多次析构行为,就需要进行深拷贝
#include <iostream>
#include <string.h>
using namespace std;
class sstring
{
public :
sstring ( const char * c_str = NULL )
{
if ( c_str == NULL )
{
_str = new char [ 1 ] ;
* _str = '\0' ;
return ;
}
int len = strlen ( c_str) ;
_str = new char [ len] ;
strcpy ( _str, c_str) ;
}
sstring ( const sstring & another)
{
int len = strlen ( another. _str) ;
_str = new int [ len] ;
_str = another. _str;
}
~ sstring ( )
{
delete [ ] _str;
}
char * c_str ( )
{
return _str;
}
private :
char * _str;
} ;
int main ( )
{
sstring s3;
cout<< s3. c_str ( ) << endl;
sstring s ( "china" ) ;
cout<< s. c_str ( ) << endl;
sstring s2 ( s1) ;
cout<< s2. c_str ( ) << endl;
return 0 ;
}