第3章 类和对象精要.pptVIP

  • 30
  • 0
  • 约2.49万字
  • 约 57页
  • 2017-05-09 发布于湖北
  • 举报
第3章 类和对象精要

3. 默认构造函数和对象数组 (1) 默认构造函数 C++规定,每个类必须有一个构造函数。若用户未显式定义一个类的构造函数,则C++提供一个默认的构造函数,也叫默认构造函数,该默认构造函数是个无参构造函数,它仅负责创建对象,而不做任何初始化工作。 例3.9 默认构造函数 #include iostream.h void main() class Tdate { { Tdate a; public: a.Set(4,12,1996); void Set(int m,int d,int y ) // 置日期值 a.Print(); { } month=m; day=d; year=y; } void Print() // 输出日期值 { coutmonth”/”day”/”yearendl; } private: int month; int day; int year; }; (2) 对象数组 对象数组是指每一个数组元素都是对象的数组。 若要说明一个带有构造函数的类的对象数组,这个类一般情况下会含有一个不带参数的构造函数或带有默认参数的构造函数。 【例3.10】对象数组1 例3.10 对象数组1 #includeiostream void main() using namespace std; { class test coutthe main :endl; { test array[5]; private: coutarray[1].getint()“ “ int num; float f1; array[1].getfloat()endl; public: } test(); test(int n, float f); // 参数化的构造函数 int getint(){return num;} float getfloat(){return f1;} }; test::test() { coutInitializing defaultendl; num = 0; f1 = 0.0; } test::test(int n, float f) { coutInitializing n, fendl; num = n; f1 = f; } 当没有为一个类定义有默认参数构造函数时,在说明对象数组时必须提供初始值,如例3.11所示。 例3.11 对象数组2 #includeiostream void main() u

文档评论(0)

1亿VIP精品文档

相关文档