【C++系列经典例子】C++默认构造,拷贝,赋值,析构四函数

本例子来自于学习视频,不是原创。首先,我们已经知道我们创建类时会有四个默认函数(实际是有6个,具体以后再探究)分别是:(以test类为例子)1.构造函数2.拷贝构造函数3.赋值函数4.析构函数以下是具体应用四个函数的过程的一个经典例子,能让我们更好的理解这四个函数的应用 代码如下:

using namespace std;

class Test
{
private:
 int value;
public:
 Test()
 {
  value = 0;
  cout << "defult create Test:" << this << endl;
 }
 Test(int t)
 {
  value = t;
  cout << "Create the Test:" << this << endl;
 }

 Test (const Test& it)
 {
  value = it.value;
  cout << "Copy create the test:" << this << endl;
 }

 Test & operator=(const Test& it)
 {
  value = it.value;
  cout << this << " = " << &it << endl;
  return *this;
 }
 ~Test()
 {
  cout << "Destory the Test:" << this << endl;
 }

 int get_value()
 {
  return value;
 }
};

Test fun(Test tp)
{
 int x = tp.get_value();
 Test tmp(x);
 return tmp;
}

int main()
{
 Test t1(10);
 Test t2;
 //Test t3();  //虽然没错,但是创建不了对象,因为规定是若要
    //调用默认的构造函数,则不需要括号,用括号会变成函数声明;
 t2 = fun(t1);
 
 cout << "main end!" << endl;
 
 return 0;
}

执行的结果分析:
关键点在于:
1.传递t1给形参时的过程
2.返回tmp实参的过程




后续的补充:
fun()函数并不是最优的方法函数,在空间和时间上进行优化:
<pre name="code" class="cpp">/*1未优化前
Test fun(Test tp)//传值操作浪费时间和空间,所以换为引用
{
 int x = tp.get_value();
 Test tmp(x);
 return tmp;
}
*/

/*2对参数传递的优化
Test fun(const Test& tp)//传值操作浪费时间和空间,所以换为引用
      //且由于tp不能改变,我们可以加上const。这样可以明显减少时间空间上
{
 int x = tp.get_value();
 Test tmp(x);
 return tmp;
}

//3对返回值的优化
Test fun(const Test& tp)
{
 int x = tp.get_value();
 //Test tmp(x);
 //return tmp;
 return Test(x);  //这里直接调用构造函数来进行构造一个无名对象进行传值,
     //这样系统就不会再创建一个临时变量来存储对象进行传值操作
}

int main()
{
 Test t1(10);
 Test t2;
 //Test t3();  //虽然没错,但是创建不了对象,因为规定是若要
    //调用默认的构造函数,则不需要括号,用括号会变成函数声明;
 t2 = fun(t1);

 cout << "main end!" << endl;

 return 0;
}



//4
Test fun(const Test& tp)
{
 int x = tp.get_value();
 Test tmp(x);
 return tmp;
}

int main()
{
 Test t1(10);
 Test t2 = fun(t1);   //编译器对这里的操作进行了优化

 cout << "main end!" << endl;

 return 0;
}
*/

//5最优解
Test fun(const Test& tp)
{
 int x = tp.get_value();
 return Test(x);
}

int main()
{
 Test t1(10);
 Test t2 = fun(t1);   //编译器对这里的操作进行了优化

 cout << "main end!" << endl;

 return 0;
}
</pre><pre name="code" class="cpp">优化最后结果已经和直接创建对象一样了
构造函数调用两次,析构函数调用两次


 
 
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值