第6章类与对象 6.2构造函数与析构函数 622析构函数 1.析构函数的特点 (1)析构函数名字为符号“~”加类名。 (2)析构函数没有参数,不能指定返回值类型。 (3)一个类中只能定义一个析构函数,所以析构函数不能重载。 (4)当一个对象作用域结束时,系统自动调用析构函数 如 CRect类的析构函数声明为:~ CRect(0; 定义为: CRect:- CRect(0 2析构函数的作用 在删除一个对象前被调用,释放该对象成员的内存空间,以 及其它一些清理工作
6.2 构造函数与析构函数 6.2.2 析构函数 1. 析构函数的特点 (1) 析构函数名字为符号“~”加类名。 (2) 析构函数没有参数,不能指定返回值类型。 (3) 一个类中只能定义一个析构函数,所以析构函数不能重载。 (4) 当一个对象作用域结束时,系统自动调用析构函数。 如CRect类的析构函数声明为:~CRect(); 定义为: CRect::~CRect() { …… } 2. 析构函数的作用 在删除一个对象前被调用,释放该对象成员的内存空间,以 及其它一些清理工作。 第6章 类与对象
第6章类与对象 例62设计一个简单的字符串类,类中有两个数据成员,分别 表示字符串的长度和字符串的内容,有一个构造函数和一个析 构函数,函数 GetLength()返回字符串长度,函数 GetContents()获得字符串的内容,重载函数 SetContents( 字符串设置值。 include <iostream .h> include <string h> class CString private int length; char *contents public CString0;∥构造函数 CString0;∥析构函数 int Getlength 0; void Getcontents(char *str); void SetContents(int len, char *cont) void Setcontents(char *cont); }
例6.2 设计一个简单的字符串类,类中有两个数据成员,分别 表示字符串的长度和字符串的内容,有一个构造函数和一个析 构函数,函数GetLength( )返回字符串长度,函数 GetContents( )获得字符串的内容,重载函数SetContents( )给 字符串设置值。 #include <iostream.h> #include <string.h> class CString { private: int length; char *contents; public: CString(); //构造函数 ~CString(); //析构函数 int GetLength(); void GetContents(char *str); void SetContents(int len, char *cont); void SetContents(char *cont); }; 第6章 类与对象