9.2 Time Class case stud Preprocessor Wrapper Test. cpp预处理 include结果 #ifndef h Preprocessor Wrapper #define h 预处理器封装 class a int a:) #endif #ifndef h #define h #ifndef h #define h #endif class af int a, 建议所有头文件均使用预处理器封装, #endif 以避免重复的头文件引用 预处理器定义: FILENAME H class b double b] 0 2018, SEU. All rights reserved. 11
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 11 9.2 Time Class Case Study --- Preprocessor Wrapper #ifndef A_H #define A_H class A{ int a;} #endif #ifndef A_H #define A_H class A{ int a;} #endif class B{ double b;} Test.cpp预处理include结果 #ifndef A_H #define A_H #endif Preprocessor Wrapper 预处理器封装 建议所有头文件均使用预处理器封装, 以避免重复的头文件引用 预处理器定义:FILENAME_H
9.2 Time Class Case Study Two ways to define member functions 类中数据成员的初始化 ●可以在类体中声明时初始化么? 复习三目运算符(?:) OA= B?C: D: 软件工程知识 ●成员函数vs全局函数(prnt函数) °面向对象编程可以通过减少传递的参数个数 程序解读(1 textbook371F92 来简化函数调用 0 2018, SEU. All rights reserved. 12
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 12 9.2 Time Class Case Study --- Two ways to define member functions 类中数据成员的初始化 可以在类体中声明时初始化么? 复习三目运算符(?:) A = B?C:D; 软件工程知识 成员函数vs全局函数 (print函数) 面向对象编程可以通过减少传递的参数个数 来简化函数调用
9.2 Time Class Case Study Two ways to define member functions 7 test. h 7/ test. h class test class test( public public void display Message void display MessageS private: cout< <num< <endI: int num } private: ∥ test. cpp int num void test: displayMessage0 cout < num < end: 相同点:均必须通过建立对象来 访问; 采用作用域运算 区别:调用方式,后者当 linline函 符定义 数调用;前者为接口与实现分离 0 2018, SEU. All rights reserved. 13
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 13 9.2 Time Class Case Study --- Two ways to define member functions // test.h class test{ public: void displayMessage(); private: int num; }; // test.cpp void test::displayMessage() { cout << num << endl; } // test.h class test{ public: void displayMessage(){ cout<<num<<endl; } private: int num; }; 相同点:均必须通过建立对象来 访问; 区别:调用方式,后者当inline函 采用作用域运算 数调用;前者为接口与实现分离 符定义
9.2 Time Class Case Study ---using class 旦定义了类,它就可以作为一种类型进行应用 ° Time sunset;∥/创建Time类的对象 Time arrayofTimes[5/建立Time类对象的数组 o Time &dinnertime sunset. ∥/对象 sunset的引用别名) °Time* timeptr1=& dinnertime;/指向对象的指 针 Tme+ timeptr.=& sunset;/指向对象的指针 程序解读 (Textbook P374 Fig9.3) 0 2018, SEU. All rights reserved. 14
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 14 9.2 Time Class Case Study --- using class 一旦定义了类,它就可以作为一种类型进行应用 Time sunset; // 创建Time类的对象 Time arrayOfTimes[5];//建立Time类对象的数组 Time &dinnerTime = sunset; // 对象sunset的引用(别名) Time *timeptr1 = &dinnerTime;//指向对象的指 针 Time *timeptr2 = &sunset;//指向对象的指针
9.2 Time Class Case Study Object Size 思考:对象有多大? sizeof(a), sizeof(a) °包括数据成员和成员函数? ●结论:只包括数据成员的大小!why? °现象: sizeof的结果将大于等于类中数 据成员的大小 0 2018, SEU. All rights reserved. 15
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 15 9.2 Time Class Case Study --- Object Size 思考:对象有多大? sizeof(A) , sizeof(a) 包括数据成员和成员函数? 结论:只包括数据成员的大小!why? 现象:sizeof的结果将大于等于类中数 据成员的大小