第二周学习:类型转换构造函数和析构函数

what is

  1. 定义转换构造函数的目的是实现类型自动转换
  2. 只有一个参数,且参数类型与类不同(不是复制构造函数),那就是转换构造函数
  3. 在需要的时候,编译系统自动调用,然后建立无名的临时对象
#include<iostream>
using namespace std;
class temp
{
    
    
	private:
		int real;
		int imag;
	public:
		temp():real(0),imag(0){
    
    }
		temp(int i):real(i),imag(0){
    
    }
		int r(){
    
    return real;
		} 
		int i(){
    
    return imag;
		}
};

int main()
{
    
    
	temp t1,t2(6);
	t1=9;    //9被自动转换为临时的temp对象 
	cout<<t1.r()<<" "<<t1.i()<<endl;
	cout<<t2.r()<<" "<<t2.i()<<endl;
}

结果
在这里插入图片描述

析构函数

  1. 对象数组生命期结束时,对象数组的每个元素的析构函数都会被调用
  2. 调用析构函数的顺序也遵循LIFO
  3. 参数对象消亡也会导致destructor的调用
  4. 返回值为value,临时对象copy也会被消亡,调用析构函数

构造函数和析构函数的调用顺序

class temp{
    
    
		int x;
	public:
		temp(int i=0):x(i){
    
    cout<<"id = "<<x<<" Constructor 
		called\n";}
		temp(const temp& j):x(j.x){
    
    cout<<"id = "<<x
		<<" Copy constructor called\n";}
		~temp(){
    
    cout<<"id = "<<x<<" Destructor called\n";} 
		temp func(const temp& t); 
};

temp temp::func(const temp& t)
{
    
    
	x=t.x;
	static temp t4(5);
	cout<<"I am here\n"; 
	return t;
}
temp t0(1);  
int main()
{
    
    
	temp t1,t2(2);
	t1=3;
	{
    
    temp t3(4);}
	t1.func(t2);

}

analyse: t0首先被调用
t1被调用,t2被调用
t1转换构造函数被调用,有生成临时对象,然后赋值然后析构函数调用
t3被调用,生命周期为块内部,析构函数调用
func成员函数被调用,静态对象t4被调用
返回值为value,临时对象copy生成,然后析构
然后析构t1,t2(先进后出),然后t4,然后t0.

在这里插入图片描述

(补:对构造函数和析构函数的理解)

构造函数不分配存储空间,类已经在内存中,然后构造函数负责初始化。析构函数不负责回收存储空间,只是负责clear

猜你喜欢

转载自blog.csdn.net/ZmJ6666/article/details/108552133
今日推荐