您的位置:首页 > 其它

析构函数

2016-03-19 21:21 204 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: