第9章关于类和对象的进一步讨论 9.1构造函数 9.2析构函数 9.3调用构造函数和析构函数的顺序 9.4对象数组 9.5对象指针 9.6共用数据的保护 9.7对象的动态建立和释放 9.8对象的赋值和复制 9.9静态成员 9.10友元 9.11类模板 2017年4月26日12时 第9章关于类和对象的进一步讨 H04 15分 论 BACK NEXT
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 2 9.1 构造函数 9.2 析构函数 9.3 调用构造函数和析构函数的顺序 9.4 对象数组 9.5 对象指针 9.6 共用数据的保护 9.7 对象的动态建立和释放 9.8 对象的赋值和复制 9.9 静态成员 9.10 友元 9.11 类模板
9.1构造函数 9.1.1对象的初始化 类的数据成员是不能在声明类时初始化的。 如果一个类中所有的成员都是公用的,则可以在定义对象时 对数据成员进行初始化。如 class Time public: /声明为公用成员 hour;minute;sec; }; Time t1={14,56,30}; /将1初始化为14:56:30 如果数据成员是私有的,或者类中有private或protected的成 员,就不能用这种方法初始化。 2017年4月26日12时 第9章关于类和对象的进一步讨 3 论 BACK NEXT
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 3 类的数据成员是不能在声明类时初始化的。 如果一个类中所有的成员都是公用的,则可以在定义对象时 对数据成员进行初始化。如 class Time { public: //声明为公用成员 hour; minute; sec; }; Time t1={14,56,30}; //将t1初始化为14:56:30 如果数据成员是私有的,或者类中有private或protected的成 员,就不能用这种方法初始化
Constructor 1.Definition: A special member function,it is primarily used to allocate memory for object and initialize the object as a particular state. 2.Characteristic: The name of constructor must be same as the class name,or else it will be regarded as a common member function. Recalled by the complier system when the object is ◆ defined. 2017年4月26日12时 第9章关于类和对象的进一步讨 论 BACK NEXT
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 4 1. Definition: A special member function, it is primarily used to allocate memory for object and initialize the object as a particular state. 2. Characteristic: uThe name of constructor must be same as the class name, or else it will be regarded as a common member function. uRecalled by the complier system when the object is defined
Constructor It can have any type of parameters,but can't have returning type.So when defining and declaring a constructor,you can't point out its type,even the “void'type. It may be inline functions,overloading functions, functions without format parameters. In practice,you usually need define a constructor for each class.If you haven't define a constructor,the complier will automatically create a constructor without a parameters. 2017年4月26日12时 H05务 第9章关于类和对象的进一步讨 论 BACK NEXT
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 5 uIt can have any type of parameters, but can’t have returning type. So when defining and declaring a constructor, you can’t point out its type, even the “void” type. uIt may be inline functions, overloading functions, functions without format parameters. uIn practice, you usually need define a constructor for each class. If you haven’t define a constructor, the complier will automatically create a constructor without a parameters
9.1.2构造函数的作用 构造函数(constructor)是一种特殊的成员函数,不需 要也不能被用户来调用它,而是在建立对象时自动 执行。 构造函数的名字必须与类名同名。 它不具有任何类型,不返回任何值。 构造函数的功能是初始化。 如果用户自已没有定义构造函数,则C+系统会自动 生成一个空的构造函数。 2017年4月26日12时 0分 第9章关于类和对象的进一步讨 论 BACK NEX
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 6 构造函数(constructor)是一种特殊的成员函数,不需 要也不能被用户来调用它,而是在建立对象时自动 执行。 构造函数的名字必须与类名同名。 它不具有任何类型,不返回任何值。 构造函数的功能是初始化。 如果用户自己没有定义构造函数,则C++系统会自动 生成一个空的构造函数