关于拷贝构造函数 (二) ——接一

 文章来源:http://www.pconline.com.cn/pcedu/empolder/gj/c/0503/570112_3.html

 

先运行下列代码:

#include <iostream
using namespace std; 
 
class Internet 

public
    Internet() 
    { 
         
    }; 
    Internet(char *name,char *address) 
    { 
        cout<<"载入构造函数"<<endl; 
        strcpy(Internet::name,name); 
    } 
    Internet(Internet &temp) 
    { 
        cout<<"载入COPY构造函数"<<endl; 
        strcpy(Internet::name,temp.name); 
        cin.get(); 
    } 
    ~Internet() 
    { 
        cout<<"载入析构函数!"; 
        cin.get(); 
    } 
protected
    char name[20]; 
    char address[20]; 
}; 
Internet tp() 

    Internet b("中国软件开发实验室","www.cndev-lab.com"); 
    return b; 

void main() 

    Internet a; 
    a=tp(); 
}

  从上面的代码运行结果可以看出,程序一共载入过析构函数三次,证明了由函数返回自定义类型对象同样会产生临时变量,事实上对象a得到的就是这个临时Internet类类型对象temp的值。

  这一下节的内容我们来说一下无名对象

  利用无名对象初始化对象系统不会不调用拷贝构造函数。

  那么什么又是无名对象呢?

  很简单,如果在上面程序的main函数中有:

  Internet ("中国软件开发实验室","www.cndev-lab.com");

  这样的一句语句就会产生一个无名对象,无名对象会调用构造函数但利用无名对象初始化对象系统不会不调用拷贝构造函数!

  下面三段代码是很见到的三种利用无名对象初始化对象的例子。

#include <iostream
using namespace std; 
 
class Internet 

public
    Internet(char *name,char *address) 
    { 
        cout<<"载入构造函数"<<endl; 
        strcpy(Internet::name,name); 
    } 
    Internet(Internet &temp) 
    { 
        cout<<"载入COPY构造函数"<<endl; 
        strcpy(Internet::name,temp.name); 
        cin.get(); 
    } 
    ~Internet() 
    { 
        cout<<"载入析构函数!"; 
    } 
public
    char name[20]; 
    char address[20]; 
}; 
 
void main() 

    Internet a=Internet("中国软件开发实验室","www.cndev-lab.com"); 
    cout<<a.name; 
    cin.get(); 
}

  上面代码的运行结果有点“出人意料”,从思维逻辑上说,当无名对象创建了后,是应该调用自定义拷贝构造函数,或者是默认拷贝构造函数来完成复制过程的,但事实上系统并没有这么做,因为无名对象使用过后在整个程序中就失去了作用,对于这种情况c++会把代码看成是:

Internet a("中国软件开发实验室",www.cndev-lab.com);

  省略了创建无名对象这一过程,所以说不会调用拷贝构造函数。

最后让我们来看看引用无名对象的情况。

#include <iostream>   
using namespace std;   
   
class Internet   
{   
public:   
    Internet(char *name,char *address)   
    {   
        cout<<"载入构造函数"<<endl;   
        strcpy(Internet::name,name);   
    }   
    Internet(Internet &temp)   
    {   
        cout<<"载入COPY构造函数"<<endl;   
        strcpy(Internet::name,temp.name);   
        cin.get();   
    }   
    ~Internet()   
    {   
        cout<<"载入析构函数!";   
    }   
public:   
    char name[20];   
    char address[20];   
};   
   
void main()   
{   
    Internet &a=Internet("中国软件开发实验室","www.cndev-lab.com");   
    cout<<a.name; 
    cin.get();   
}

  引用本身是对象的别名,和复制并没有关系,所以不会调用拷贝构造函数,但要注意的是,在c++看来:

Internet &a=Internet("中国软件开发实验室","www.cndev-lab.com");

  是等价与:

Internet a("中国软件开发实验室","www.cndev-lab.com");

  的,注意观察调用析构函数的位置(这种情况是在main()外调用,而无名对象本身是在main()内析构的)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值