类的默认构造函数为何使用引用以及什么时候显式的给出 沉沉_

先上一段简单代码:

#include<iostream>

using namespace std;

class test
{
public:
 test()
 {
  cout<<"默认构造函数"<<endl;
 }

 ~test()
 {
  cout<<"析构函数"<<endl;
 }

 void fun1(test & t)
 {
  cout<<"fun1 called"<<endl;
 }

 void fun2(test t)
 {
  cout<<"fun2 called"<<endl;
 }
};

int main()
{
 test t1;
 
 test t2(t1);
 t2.fun2(t2);
 t1.fun1(t2);


 return 0;
}

执行结果:
默认构造函数
fun2 called
析构函数
fun1 called
析构函数
析构函数
         对上述执行结果进行分析,可知程序本身显式的创建两个test类的对象,但是默认构造函数只执行了一次,而析构函数却执行了三次。由于构造函数可以有多个版本,而析构函数只有一个版本:有么默认,要么自己提供。所以程序供创建了三个test类的对象。而执行结果只调用了一个构造函数则是由于默认的拷贝构造函数的存在。既然存在默认的拷贝构造函数,那么他的形式是什么样的?又是什么时候被调用的?使用的过程中又该注意什么问题?
 
--未完待续
 
原文地址:https://www.cnblogs.com/chenchenluo/p/2223662.html