Mr_Visionary 2020-04-12 15:07 采纳率: 66.7%
浏览 299
已采纳

为什么会调用拷贝构造函数与析构函数

c++ 课本上的题
代码如下:

include

using namespace std ;
class A
{
int x,y;
public:
A ( ) { cout << "in A's default constructor \n "; }
A ( const A & ) { cout <<"in A's copy constructor \n ";}
~A ( ) {cout <<" in A's destructor \n " ;}
virtual void f() {cout << " in A's f\n " ;}
void g() { cout << " in A's g\n ";}
void h() {f();g();}
};
class B : public A
{ int z;
public:
B(){ cout << " in B's default constructor\n" ; }
B(const B& ) { cout << "in B's copy constructor\n";}
~B ( ){ cout << " in B's destructor\n " ;}
void f ( ) { cout << " in B's f\n " ;}
void g ( ) { cout << " in B's g\n ";}
};

void func1 (A x)
{x.f();
x.g();
x.h();
}
void func2 (A &x)
{x.f();
x.g();
x.h();
}

int main ()
{
cout<<"------Section 1-------\n";
A a;
A *p= new B;
cout<<"------Section 2-------\n";
func1(a);
cout<<"------Section 3-------\n";
func1(*p);
cout<<"------Section 4-------\n";
func2(a);
cout<<"------Section 5-------\n";
func2(*p);
cout<<"------Section 6-------\n";
delete p;
cout<<"------Section 7-------\n";
return 0;
}
为什么在section2 和section3 中调用了A 的拷贝构造函数与析构函数?

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-04-12 15:34
    关注

    调用函数传入a的时候,如果不是引用,就需要在堆栈上创建一个a的副本,这个就要拷贝构造函数
    函数退出,就会调用析构函数

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭