构造函数、析构函数、虚析构函数

构造函数:

说析构函数之前,先说下构造函数。

构造函数用来完成对对象的一系列初始化操作,主要作用有:

1.给创建的对象建立一个标识符

2.为对象数据成员开辟内存空间

3.完成对象数据成员的初始化

当并未显示的定义构造函数时,会生成一个默认的构造函数,默认构造函数不能完成对象数据成员的初始化,只能给对象创建一标识符,并为对象中的数据成员开辟一定的内存空间。

实例1:

#include <iostream>
using namespace std;
class Point
{
public:
	Point()//声明并定义构造函数
	{
		cout << "调用构造函数" << endl;
		xPos = 100;
		yPos = 100;
	}
	void printPoint()
	{
		cout << "xPos = " << xPos << endl;
		cout << "yPoss = " << yPos << endl;
	}
private:
	int xPos;
	int yPos;
};
int main()
{
	Point M;
	M.printPoint();
	system("pause");
	return 0;
}

 

实例2:

#include <iostream>
using namespace std;
class Point
{
public:
	Point(int x = 0,int y = 0)//带有参数的构造函数
	{
		cout << "调用构造函数" << endl;
		xPos = x;
		yPos = y;
	}
	void printPoint()
	{
		cout << "xPos = " << xPos << endl;
		cout << "yPoss = " << yPos << endl;
	}
private:
	int xPos;
	int yPos;
};
int main()
{
	Point M(10, 20);
	M.printPoint();
	Point N(100);
	N.printPoint();
	Point P;
	P.printPoint();
	system("pause");
	return 0;
}

实例3:

#include <iostream>
using namespace std;
class Point
{
public:
	/*Point(int x = 0, int y = 0)//带有参数的构造函数
	{
		cout << "调用构造函数" << endl;
		xPos = x;
		yPos = y;
	}*/
	Point(int x = 0, int y = 0) :xPos(x), yPos(y)//使用初始化表进行初始化
	{
		cout << "使用初始化表进行初始化" << endl;
	}
	void printPoint()
	{
		cout << "xPos = " << xPos << endl;
		cout << "yPoss = " << yPos << endl;
	}
private:
	int xPos;
	int yPos;
};
int main()
{
	Point M(10, 20);
	M.printPoint();
	Point N(100);
	N.printPoint();
	Point P;
	P.printPoint();
	system("pause");
	return 0;
}

 析构函数:

编译器会为对象生成一个默认的析构函数,用于对成员撤销时的一些清理工作。但默认生成的析构函数只能释放类的普通成员所占的空间,无法释放通过new或malloc申请的空间,所以需要显式的定义析构函数对这些申请的空间进行释放,避免造成内存泄漏。

#include <iostream>
using namespace std;
class Line
{
public:
	void setLength(double len);
	double getLength();
	Line();//构造函数
	~Line();//析构函数
private:
	double length;
};
Line::Line()
{
	cout << "构造函数" << endl;
}
Line::~Line()
{
	cout << "析构函数" << endl;
}
void Line::setLength(double len)
{
	length = len;
}
double Line::getLength()
{
	return length;
}
int main()
{
	Line line;
	line.setLength(6.0);
	cout << "Length of Line:" << line.getLength() << endl;
	system("pause");
	return 0;
}

虚析构函数:

#include <iostream>
using namespace std;
class Base
{
public:
	Base() {};
	virtual ~Base() 
	{
		cout << "Base的析构函数" << endl;
	};
	virtual void DoSomething()
	{
		cout << "Do something in Base" << endl;
	}
};
class Derived :public Base
{
public:
	Derived() {};
	~Derived() 
	{
		cout << "Derived的析构函数" << endl;
	}
	void DoSomething()
	{
		cout << "Do something in Derived" << endl;
	}
};
int main()
{
	Base* p = new Derived;
	p->DoSomething();
	delete p;
	system("pause");
	return 0;
}

运行结果:

使用基类声明的变量类型,指向派生类时,调用派生类的析构函数时同样会调用基类的析构函数。

但是当去掉基类的虚析构函数前的virtual时,运行结果如下:

可知,并未对继承类进行析构,则会造成内存泄漏,这就是虚析构函数的作用:当使用一个基类的指针删除一个派生类的对象时,派生类的析构函数同样会被调用。

猜你喜欢

转载自blog.csdn.net/N1neDing/article/details/81750193