C++中函数调用返回自定义类型对象(一)

本文通过一个C++示例程序详细解析了构造函数与复制构造函数的区别及调用时机,展示了临时对象如何影响复制构造函数的调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class  ca   
{};   
ca f()   
{   
          ca   x;   
          
return
   x;   
}   
int
  main()   
{
ca  y
=
 f();
return 0
;
}   

中间过程是有临时对象产生的  
  这个过程相当于:  
  ca类型的临时变量   =   f();  
  ca   y   =   ca类型的临时变量;   
#include <iostream>   
#include 
<string>
   
using namespace
 std;

class
 ca   
{
public
:   
  ca()   
  {   
    cout
<<"ca()"<<
endl;   
  }   
  ca(ca
&
   ca)   
  { 
    cout
<<"ca(ca& ca)"<<
endl;   
  }
  
~
ca()
  {
    cout
<<"~ca()"<<
endl;   
  }  
    
};   
    
ca f()
{
    ca x;   
    
return
 x;
}   
    
int
 main()
{   
    ca y;
    y
=
f();   
    system(
"pause"
);
    
return 0
;
}

 

输出结果:

ca()
ca(ca& ca)
~ca()
请按任意键继续 . . .
~ca()

 若将上述主函数中的代码

 

    ca y=f();  

改为:

    ca y;
    y
=
f();  

输出结果为:

ca()
ca()
ca(ca
&
 ca)
~
ca()
~
ca()
请按任意键继续 . . .
~ca()

结论:

ca类型的临时变量   =   f();     //这儿构造临时变量要调用ca(ca&   ca).  
  ca   y   =   ca类型的临时变量;   //这儿构造y   也调用ca(ca&   ca).  
   
  ca   y   =   x;   和   ca   y(x);   是一样的.都是ca(ca&   ca).

ca   y;     //这儿是ca()  
  y   =   x;   //   这儿是operator=  
   
  和   ca   y   =   x   ;   不一样的.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值