c++拷贝构造函数

转一篇博客:

http://blog.csdn.net/lwbeyond/article/details/6202256/

介绍拷贝构造函数很详细

总结

可见,拷贝构造函数是一种特殊的构造函数,函数的名称必须和类名称一致,它必须的一个参数是本类型的一个引用变量

拷贝构造函数也是构造函数

调用了拷贝构造函数就不会调用构造函数

#include <iostream>
using namespace std;

class A
{
public:
string name;
A(){name = "initial";}
A(string a){name = a; cout << "create:" << name << endl;}
A(const A &a){name = a.name + "copy"; cout << "create:" << name << endl;}

};
int main()
{
 A a("a");
 A b(a);
}

 输出结果是:

create:a
create:acopy

说明拷贝构造时没有调用构造函数(相当于构造函数重载?)

以下是拷贝构造函数一个应用,运行一次程序就知道是什么意思了

#include <iostream>
using namespace std;


    class CExample   
    {  
    private:  
     int a; 
     string name; 
      
    public:  
     //构造函数  
     CExample(string a)  
     {   
      name = a;
      cout<<"creat: "<< name <<endl;  
     }  
      
     //拷贝构造  
     CExample(const CExample& C)  
     {  
      name = C.name + "copy" ;  
      cout<<"create:"<< name <<endl;  
     }  
       
     //析构函数  
     ~CExample()  
     {  
      cout<< "delete: "<< name <<endl;  
     }  
      
         void Show ()  
     {  
             cout<<a<<endl;  
         }  
    };  
      
    //全局函数,传入的是对象  
    void g_Fun(CExample C)  
    {  
     cout<<"test"<<endl;  
    }  
      
    int main()  
    {  
     CExample test("a");  
     //传入对象  
     g_Fun(test);  
      
     return 0;  
    }  

程序输出是

creat: a
create:acopy
test
delete: acopy
delete: a

Cexample(Dexample)也是拷贝构造

posted @ 2017-03-29 11:06  每天一点积累  阅读(227)  评论(0)    收藏  举报