析构函数
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; }
相关文章推荐
- Linux操作系统下的三种Java环境配置方法
- dB单位含义及换算
- 【转】ORA-12154: TNS: 无法解析指定的连接标识符
- 嵌入式 十个最值得阅读学习的C开源项目代码
- 20160319tomcat自定义web应用主页以及Context部分属性意义以及什么是servlet
- 微信开发环境搭建
- 学习进度条
- LeetCode 11. Container With Most Water
- 《Linux内核分析》 第四周
- 函数递归简单题-hdoj-2044 2018-一只小蜜蜂 母牛的故事
- [LeetCode][Java][JavaScript]Counting Bits
- 【CodeForces】[651A]Joysticks
- ASP.NET 宏观总结
- 全栈工程师笔记
- ActiveX、COM、OLE的关系
- ubuntu访问windows共享
- C++并行开发Pthread之线程(一)
- one-hot编码
- 2016年第11周六
- *J2EE中乱码处理