2010.4.4学习笔记

来源:互联网 发布:淘宝重复铺货 编辑:程序博客网 时间:2024/06/16 00:45

1.构造函数、析构函数、拷贝构造函数

其中copy constructor有三种情况:

(1)If an object is initialized by another object of the same class, the copy constructor is invoked automatically.

      B=A;

      B(A);

 (2)  If the arguments of the function is an object of a class, the copy constructor is invoked when the function is invoked.

eg:void fun1(Point p){  
           cout<<p.GetX()<<endl;
      }
      void main(){  
           Point A(1,2);
           fun1(A); // copy constructor is invoked
      }
(3)If the function returns an object of a class, the copy constructor is invoked.
eg:   Point fun2(){   
            Point A(1,2);
            return A; //copy constructor is invoked
       }
       void main(){
             Point B;
            B=fun2();
      }

 深拷贝和浅拷贝:

string s1("hello"),s2;

s2=s1;

浅拷贝:指针s1,s2指向了同一段内存。

Default copy constructor.

Only copy the address of the resource

深拷贝:为被赋值的对象新开辟了一段内存。

User-defined copy constructor
Can copy the resource

 

2 explicit  关键字

This keyword is a declaration specifier that can only be applied to in-class constructor declarations. An explicit constructor cannot take part in implicit conversions. It can only be used to explicitly construct an object.
首先explicit只能在类内部的构造函数中使用

如果被声明为explicit,那么只能显示的调用构造函数。

A(1,2);

不能隐式转换来调用构造函数.

B=A;

反义词(implicit,隐晦的,含蓄的)

 

原创粉丝点击