MOOC清华《面向对象程序设计》第3章:拷贝构造函数实验

来源:互联网 发布:手机wifi扫描不到网络 编辑:程序博客网 时间:2024/06/06 02:23
#include <iostream>using namespace std;class Test{public:Test(){cout << "Test()" << endl;}//缺省构造函数 Test(const Test& src){cout << "Test(const Test&)" << endl;}//拷贝构造函数 ~Test(){cout << "~Test()" << endl;}//析构函数 };void func1(Test obj){cout << "func1()..." << endl;}//类作为参数类型 Test func2(){cout << "func2()..." << endl;return Test();//返回缺省构造函数 }//类作为返回类型 int main(){cout << "main()..." << endl;Test t;func1(t);t = func2();return 0;}


测试结果说明:
第二行的 Test() 是对象 t 在构造时调用的缺省构造函数;
第三行的 Test(const Test&) 是以对象 t 为源(source,简写为src)生成一个新的对象,传给 func1() ,所以调用了拷贝构造函数;
第五行的 ~Test() 是 func1() 退出时,把参数 t 释放掉,所以调用了析构函数;
第七行的 Test() 是 func2() 返回一个构造函数时,调用的构造函数;
第八行的 ~Test() 是把 func2() 产生的临时对象给释放掉,调用的析构函数;
最后一行的 ~Test() 是 main 函数退出时,局部变量 t 被释放所调用的析构函数。

阅读全文
0 0
原创粉丝点击