Chinaunix首页 | 论坛 | 博客
  • 博客访问: 359781
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: C/C++

2011-04-21 16:26:17

  •  what is copy constructor, and where it 's require?

copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object. The first argument of such a constructor is a reference to an object of the same type as is being constructed (const or non-const), which might be followed by parameters of any type (all having default values).

Normally the compiler automatically creates a copy constructor for each class (known as a default copy constructor) but for special cases the programmer creates the copy constructor, known as auser-defined copy constructor. In such cases, the compiler does not create one.

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file, in which case a destructor and an assignment operator should also be written (Rule of three).

  1. string ( const string& str );  
  2. //Constructs a standard  object and initializes its content.
  3. //Content is initialized to a copy of the  object str.
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;

  4. int
  5. main(void)
  6. {
  7.         string base = "hello world";
  8.         string str (base);

  9.         cout << str << endl;

  10.         return (0);
  11. }

阅读(964) | 评论(1) | 转发(0) |
0

上一篇:String VI Operation

下一篇:calloc 和 malloc

给主人留下些什么吧!~~

onezeroone2011-04-24 16:26:43

reate a new object as a copy of an existing object