C++ 构造函数与析构函数

1、什么是构造函数/析构函数:

  首先,他们都是类的成员函数,名字和类名相同(析构在类名前加‘~’),没有返回值,没有void且可被重载。若用户未自定义,则编译器自动生成,其最大的特点就是类定义对象(或对象消亡)时自动运行的一个函数。

2、实例分析

#include <iostream>

using namespace std;


class A
{
	public:
		int a;
		A();
		A(int i);
		~A();
};

A::A(void)
{
	 a = 5;
	 cout << "This is A" << endl;
}




A::A(int i)
{
	 a = i;
	 cout << "This is A" << endl;
}

A::~A()
{
	 cout << "This is ~A" << endl;
}



int main(void)
{
	A c;
	A D(100);
	
	cout << "c: " << c.a  << endl;
	
	cout << "D: " << D.a  << endl;
	
	return 0;
}

 

运行打印的结果是:

This is A
This is A
c: 5
D: 100
This is ~A
This is ~A

--------------------------------
Process exited after 0.2047 seconds with return value 0
请按任意键继续. . .

由以上结果对应定义中的“类定义对象时自动执行”。

3、类继承时的的构造/析构函数

#include <iostream>

using namespace std;


class A
{
	public:
		int a;
		A();
		A(int i);
		~A();
};

A::A(void)
{
	 a = 5;
	 cout << "This is A" << endl;
}




A::A(int i)
{
	 a = i;
	 cout << "This is A" << endl;
}

A::~A()
{
	 cout << "This is ~A" << endl;
}

class B : public A
{
	public:
		char c;
		B();
		B(char i);
		~B();
};
B::B(void)
{
	c = 'a';
	cout << "this is b2" << endl;
}

B::B(char i)
{
	c = i;
	cout << "this is b1" << endl;
}  

B::~B()
{
	cout << "this is ~B" << endl;
}

int main(void)
{
/**********************
	A c;
	A D(100);
	
	cout << "c: " << c.a  << endl;
	
	cout << "D: " << D.a  << endl;
****************************/
   B c;
   B d('z');
   cout << "c: " << c.c  << endl;
	
	cout << "d: " << d.c  << endl;
   
	
	return 0;
}


 

其结果为:

This is A
this is b2
This is A
this is b1
c: a
d: z
this is ~B
This is ~A
this is ~B
This is ~A

--------------------------------
Process exited after 0.3514 seconds with return value 0
请按任意键继续. . .

由以上结果可以知道,基类的构造函数先被执行,析构函数后被执行(这是重点,面/笔试中经常有)。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值