1、构造函数
类的一种特殊的成员函数,它会在每次创建类的对象时执行。构造函数的名称与类的名称完全相同,并不会返回任何类型,也不会返回void(无类型)。
作用:初始化对象的数据成员。
①默认构造函数
class Shape { public: Shape();//Shape构造函数 void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getWidth() { return width; } int getHeight() { return height; } private: int width; int height; }; //定义Shape构造函数 Shape::Shape(void) { cout << "Shape已经被创建" << endl; }
②带参数的构造函数
构造函数带参数,这样在创建对象时就会给对象创建初始值。
class Shape { public: Shape(int w,int h);//带参数的Shape构造函数 void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getWidth() { return width; } int getHeight() { return height; } private: int width; int height; }; //定义带参数的Shape构造函数 Shape::Shape(int w,int h) { cout << "Shape已经被创建" << endl; cout << "宽为" << w << endl; cout << "高为" << h << endl; }