对象在被创建时,要被初始化,用到的就是构造函数。换句话说,构造函数的作用就是初始化对象。
析构函数是用来释放对象的内存的。
在类中定义构造函数和析构函数
例
class Point { public: Point(int x, int y) { X = x; Y = y; cout << "Constructor is called"; displayxy(); } void displayxy() { cout << "(" << X << "," << Y << ")" << endl; } ~Point() { cout << "Destructor is called"; displayxy(); } private: int X, Y; };
还可在类中声明,在类外定义
例
class Point { public: Point(int x, int y); void displayxy(); ~Point(); private: int X, Y; }; Point::Point(int x, int y) { X = x; Y = y; cout << "Constructor is called"; displayxy(); } void Point::displayxy() { cout << "(" << X << "," << Y << ")" << endl; } Point::~Point() { cout << "Destructor is called"; displayxy(); }
::是作用域运算符,表明其后的成员函数是在此类中声明的
析构函数在程序结束时自动调用,以下为上述代码的输出结果
复制构造函数(又叫拷贝构造函数)
它的作用是用一个已经存在的对象去初始化另一个对象,为了保证所引用的对象不被修改,通常把引用参数声明为const参数。
例
<类名>::<类名>(const <类名> & <对象名> ) { <函数体> }
它在以下情况会被自动调用:
- 当用类的一个对象去初始化该类的另一个对象时。
- 当函数的形参是类的对象,进行形参和实参结合时。
- 当函数的返回值是类的对象,函数执行完成返回调用者时。
例:
- Point p2=p1;//用对象p1创建新对象p2,调用了复制构造函数
- p2=func(p1);//在func()中,调用复制构造函数,当用p1初始化形参p时,给对象p赋值
- return pp;//pp是对象。当执行return pp;时,用对象pp创建一个临时对象,调用了复制构造函数