类和对象基础———类型转换构造函数、析构函数

类型转换函数基本概念:

1:定义转换构造函数的目的是实现类型的自动转换。
2:只有一个参数,而且不是复制构造函数的构造函数, 一般就可以看作是转换构造函数。
3:当需要的时候,编译系统会自动调用转换构造函数, 建立一个无名的临时对象(或临时变量)。

具体实例:

class Complex {
	 public: 
 		double real, imag;
 		Complex( int i) {//类型转换构造函数
			cout << "IntConstructor called" << endl;
			real = i; imag = 0; 
 		}
 		
		Complex(double r,double i) {real = r; imag = i; }
};
int main ()
{
	Complex c1(7,8);
	Complex c2 = 12;   //这里也调用了类型转换构造函数
	c1 = 9; // 9被自动转换成一个临时Complex对象
	
	cout << c1.real << "," << c1.imag << endl;
	
 	return 0;
}

结果输出:0,9

析构函数基本概念:

1:名字与类名相同,在前面加‘~’, 没有参数和返回值,
2:一个类最多只能有一个析构函数 。 析构函数对象消亡时即自动被调用 。可以定义析构函数来在对象消亡前做善后工作,比如释放分配的空间等。
3:如果定义类时没写析构函数,则编译器生成缺省析构函数。缺省析构函数什么也不做。
4:如果定义了析构函数,则编译器不生成缺省析构函数。

析构函数实例:

class String{
	private :
		char * p;
	public:
		String () {
			p = new char[10];
		}	
		~ String () ;
};

String ::~ String()//在这里定义了一个析构函数
{
delete [] p;
}

析构函数和数组:

对象数组生命期结束时,对象数组的每个元素的析构函数都会被调用。

若new一个对象数组,那么用delete释放时应该写 []。否则只delete一个对象(调用一次析构函数)

class Ctest {
	public:
		~Ctest() { cout<< "destructor called" << endl; }
};

int main () {
	Ctest array[2];
	cout << "End Main" << endl;
	return 0;
}

析构函数在对象作为函数返回值返回后被调用:

class CMyclass {
	public:
		~CMyclass() { cout << "destructor" << endl; }
};

CMyclass obj;
CMyclass fun(CMyclass sobj ) { //参数对象消亡也会导致析,构函数被调用

		return sobj; //函数调用返回时生成临时对象返回
		
}
int main(){
	obj = fun(obj); //函数调用的返回值(临时对象)被用过后,该临时对象析构函数被调用。
	return 0; 
}

总结:构造函数和析构函数什么时候被调用?

class Demo {
	int id;
	public:
		Demo(int i) {
			id = i;
			cout << "id=" << id << " constructed" << endl;
		}

		~Demo() {
			cout << "id=" << id << " destructed" << endl;
		}
};

Demo d1(1);          //全局对象在main函数还没有执行时就被创建
void Func() 
{
	static Demo d2(2);   //静态局部变量,整个程序结束时,这个被创建的对象才会消亡
	Demo d3(3);
	cout << "func" << endl;
}
int main () {
	Demo d4(4);
	d4 = 6;
	cout << "main" << endl;
	
	{ Demo d5(5);  }
	
	Func();
	cout << "main ends" << endl;
	return 0;
}

输出结果如下:

id=1 constructed 
id=4 constructed
id=6 constructed
id=6 destructed
main
id=5 constructed
id=5 destructed
id=2 constructed
id=3 constructed
func
id=3 destructed
main ends
id=6 destructed
id=2 destructed
id=1 destructed

猜你喜欢

转载自blog.csdn.net/qq_44923545/article/details/105903209