析构函数

#include <iostream>
#include <string>

using namespace std;

class NoName
{
public:
	NoName() :pstring(new std::string), i(0), d(0)
	{
		// 打开文件
		// 连接数据库
		// 动态分配内存
		cout << "构造函数被调用了," << endl;
	}
	NoName(const NoName & other); // 复制构造函数,函数的声明,
	~NoName();  // 这是析构函数与构造函数成对出现,
	// 析构函数是释放资源,构造函数是获取资源,C++会自动的写析构函数,
	NoName& operator = (const NoName &rhs);  // 赋值操作符,
private:
	std::string *pstring;
	int i;
	double d;
};

NoName& NoName::operator = (const NoName &rhs)
{
	pstring = new std::string;
	*pstring = *(rhs.pstring);
	i = rhs.i;
	d = rhs.d;
	return *this;
}

NoName::NoName(const NoName & other)
{
	pstring = new std::string;
	*pstring = *(other.pstring);
	i = other.i;
	d = other.d;
}

NoName::~NoName()
{
	// 关闭文件
	// 关闭数据库连接
	// 回收动态分配的内存,
	cout << "析构函数被调用了," << endl;
	delete pstring;
}

int main()
{
	NoName a;
	NoName *p = new NoName;

	cout << "hello" << endl;

	delete p;
	return 0;
}

你可能感兴趣的:(析构函数)