构造函数:当一个对象被创建时,通过构造函数将对象中的值初始化为特定的值;
析构函数:执行对象消失前的清尾工作,在对象生存期快要结束时候自动调用的;
实例:
#include <iostream>
using namespace std;
class Point{
public :
Point(int xx, int yy) //构造函数 定义为有参数
{
x = xx;
y = yy;
};
Point (){
int x = 0, y = 0;
};//默认构造函数 即无参数
Point(Point &p);// 复制构造函数
int getX()
{
return x;
}
int getY()
{
return y;
}
private:
int x, y;
};
Point::Point(Point &p)//复制构造函数
{
x = p.x;
y = p.y;
}
Point f()
{
Point c(3,4);
return c;
}
int main()
{
Point a(1, 2);
Point b = a;//将a复制给b
Point c(a);//a复制给c, 和上个语句操作一样
cout << b.getX() << endl;
cout << a.getX() << endl;
Point C();//调用默认无参的构造函数
Point d;
d = f();
cout << d.getX() << endl;
return 0;
}
析构函数:
class clock:{
public:
clock();
void settime(int hh, int mm, int ss);
void showtime();
~clock();//析构函数
private:
int h, m, s;
};