首页 新闻 会员 周边

C++类的拷贝构造函数什么时候被调用?

0
[已解决问题] 解决于 2016-04-17 08:12
#include<iostream>
using namespace std;
class Complex
{
    private:
     double real;
     double imag;
    public:
     Complex(double r=0,double i=0)
     {
         cout<<" constructing···\n";
      real=r;
      imag=i;
     }
     Complex(Complex &c)
     {
         cout<<"copy constructing···\n";
      real=c.real;
      imag=c.imag;
     }
     ~Complex()
     {
      cout<<"destructing···\n";
     }
     double realcomplex()
     {
      return real;
     }
     double imagcomplex()
     {
      return imag;
     }
};
void display(Complex p)
{
     cout<<"The real of complex="<<p.realcomplex()<<endl;
     cout<<"The imag of complex="<<p.imagcomplex()<<endl;
}
int main()
{
     Complex a(1.1,2.2);
     Complex b;
     Complex c(a);
     display(a);
     display(b);
     display(c);
 return 0;
}


constructing···
constructing···
copy constructing···
copy constructing···
The real of complex=1.1
The imag of complex=2.2
destructing···
copy constructing···
The real of complex=0
The imag of complex=0
destructing···
copy constructing···
The real of complex=1.1
The imag of complex=2.2
destructing···
destructing···
destructing···
destructing···


Process returned 0 (0x0) execution time : 0.891 s
Press any key to continue.

该程序中的拷贝构造函数在不同的时刻被调用了三次,为什么会成这种情况,我主要想问拷贝构造函数什么时候被调用?
c++
生成风的主页 生成风 | 初学一级 | 园豆:189
提问于:2015-11-06 20:51
< >
分享
最佳答案
1

楼主的拷贝构造函数被执行了四次,而且一看楼主就不是纯粹的菜鸟。简单说一下,楼主应该就明白了。

第一次   Complex c(a); 执行了拷贝构造函数, a->c   
第二次   display(a); 执行了拷贝构造函数 a->p(p就是void display(Complex p)中的p)

第三次   display(b); 执行了拷贝构造函数 b->p(p就是void display(Complex p)中的p)
第四次   display(c); 执行了拷贝构造函数 c->p(p就是void display(Complex p)中的p)

楼主应该清楚了吧。

奖励园豆:5
爱克斯贼冀 | 菜鸟二级 |园豆:215 | 2015-11-20 08:45

所以说,是在传参的时候调用了复制构造函数,而且该函数一经执行完,临时对象就被析构了!你想表达的就是这么一个意思吧?

生成风 | 园豆:189 (初学一级) | 2015-11-20 13:04

@生成风:  对,其实已楼主的水平仔细一样自己就想清楚了。

爱克斯贼冀 | 园豆:215 (菜鸟二级) | 2015-11-20 13:23

@mrx2015: .....不经常用就会忘,还是对一些基础的知识点不敏感啊!谢了!!!

生成风 | 园豆:189 (初学一级) | 2015-11-20 13:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册