1 / 48

C++ Programming Lecture 14

C++ Programming Lecture 14. Wei Liu ( 刘威 ) Dept. of Electronics and Information Eng. Huazhong University of Science and Technology Feb. 2014. Lecture 14. Chapter 16. Introduction to Class and Object 16.1 Introduction 16.2 Classes, Objects, Member Functions and Data Members

chun
Download Presentation

C++ Programming Lecture 14

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ ProgrammingLecture 14 Wei Liu (刘威) Dept. of Electronics and Information Eng. Huazhong University of Science and Technology Feb. 2014

  2. Lecture 14 • Chapter 16. Introduction to Class and Object • 16.1 Introduction • 16.2 Classes, Objects, Member Functions and Data Members • 16.3 Overview of the chapter examples • 16.4 Defining a class • 16.5 Defining a member function • 16.6 Data member • 16.7 Initializing object with constructors • 16.8 Separate file • 16.10 Validating data with set function

  3. 16.2 Classes, Objects • In real world • Class(类) is the abstract description on the common characteristics of one category of objects(对象的抽象) • such as the design diagram, blueprint of a kind of car • Object(对象) is one solid instance of the conception of class(类的实例), realizing the common attributes with real values • such as a user-defined car product

  4. 16.2 Classes, Objects • In object-oriented programming • Class(类) is a description of the data structures(数据结构), methods and default values for a type of object • Attributes(属性): the data structures of variable, constant, … • Methods(方法/行为): the name of function in object-oriented design • Default values(缺省值): initialization on every attribute, i.e., the attributes given at birth data members member functions Naming in Object-oriented Methodology Naming in C++ Language

  5. 16.2 Classes, Objects • In object-oriented programming • Class(类) is a description of a type of object. • Object(对象) is a region of memory implementing(实现) the class • Object lives in memory, its attributes are with values and can be accessed, its methods are with entry address and can be called • Objects of the same class have different memory for their attributes but the same memory entries for their methods. Same methods Different attributes when implementing Your car, attributes { Toyota, Red, 100000km } My car, attributes { VW Polo, Sliver, 80000km }

  6. 16.2 More on Classes • In real world • The characteristics of class may have different access levels for different users • Protected data: such as the car data for 4S car-dealers • Public data: such as the panel data for every users Read from dealer: Wliu’s car, attributes { VW Polo, engine model, gas sensor value, …} Read from user: Wliu’s car, attributes { VW Polo, Sliver color, 80000km, …}

  7. 16.2 More on Classes • In object-oriented programming • The scope of attributes and methods can be different • Private(私有): can only be accessed by the object itself • Protected(保护): can be accessed by not only itself, but the ``friends’’ • Public(共有): can be accessed by everybody Private: … Protected: … Public: … Data members Private: … Protected: … Public: … Member functions

  8. Summary • Object-oriented programming • Class and object • Class describes the attributes and the methods • An object is an instance of the class, which can be visited by program • It is data-centered (以数据为中心,信息封装,信息隐藏) • Data members are hiding from the outside • Member functions are defined to access data members • It is message-driven (消息驱动) • Calling the member function: send a message to the object • Return of member function: response of the object • Public • inaccessible “Access Denied” “How much money?” “Three” “How many boxes?” • Public • accessible

  9. Lecture 14 • Chapter 16. Introduction to Class and Object • 16.1 Introduction • 16.2 Classes, Objects, Member Functions and Data Members • 16.3 Overview of the chapter examples • 16.4 Defining a class • 16.5 Defining a member function • 16.6 Data member • 16.7 Initializing object with constructors • 16.8 Separate file • 16.10 Validating data with set function

  10. 16.3 Grades book • Grades book • (教师成绩簿) • Used to record the grades of students in one class One sample page of real grade book

  11. 16.4 Defining Class • Analyze requirement • Design the class in UML Open the gradebook Display welcome message Class Name Data members(None) Public accessible Member functions

  12. 16.4 Defining Class Class Definition (类的定义) 创建类的一个对象 ClassNamemyObjectName; 访问对象的一个成员函数 myObjectName.MemberFunction();

  13. 16.4 Defining Class • Comments on this class definition • It is a big statement “ { } ; ” • It have Access specifier: private, protected, public • It have one member function • Function can be defined without declaration in class definition • This faction just do actions, without any return value (void) • Naming style: ClassName, myObjectName, myFunctionName Definition of a member function (成员函数的定义) 成员访问说明符public + 冒号

  14. Lecture 14 • Chapter 16. Introduction to Class and Object • 16.1 Introduction • 16.2 Classes, Objects, Member Functions and Data Members • 16.3 Overview of the chapter examples • 16.4 Defining a class • 16.5 Defining a member function • 16.6 Data member • 16.7 Initializing object with constructors • 16.8 Separate file • 16.10 Validating data with set function

  15. 16.5 Defining a member function • Analyze requirement • Design the class in UML Open the gradebook Display the course name as user want Class Name Data members(None) Public accessible Member functions

  16. 16.5 Defining a member function • Design the data structure • No data member is required by the class now, the input courseName will be stored temporally • Sample courseName: “C++ Programming” • Input Issue • Problem • The space between words will be considered as the break of two inputs by std::cin • Solution • the type of string is adopted for courseName • “string” is a data type (or class) defined in standard C++ library <string> • Function getline() can accept all chars in one line including spaces

  17. 16.5 Defining a member function Enable the string library #include <string> Member Function with input parameter

  18. Temporally string variable getline(cin,stringObject) 从cin输入流获取stringObject

  19. Summary • Definition of a Class with member functions • Create a object instance of the class, class is also a type! • Calling the member function of an object classClassName { public: voidmemberFunctionName() { // … } }; // create an object ClassNamemyObjectName; // call object'sfunction myObjectName.myFunctionName();

  20. Lecture 14 • Chapter 16. Introduction to Class and Object • 16.1 Introduction • 16.2 Classes, Objects, Member Functions and Data Members • 16.3 Overview of the chapter examples • 16.4 Defining a class • 16.5 Defining a member function • 16.6 Data member • 16.7 Initializing object with constructors • 16.8 Separate file • 16.10 Validating data with set function

  21. 16.6 Data member • Analyze requirement • Design the class in UML User input the course name Get the course name Private data: Course name Open the gradebook Display the course name Class Name Data members Private accessible Two functions are defined to set/get the private data Member functions

  22. 16.6 Data member Set/get functions are atomic operations for data members, called by other functions Member functions: public access Data member: private access Declaration of data member

  23. Call member function to get data member Call member function to set data member Call member function to show data member

  24. Experiment • 设计一个日期类 • 包括月、日信息作为数据成员 • 打印一条提示信息“date is xx-xx”

  25. Summary • Declaration of a Class with data members • Data members are access-able by member functions, no need to declare in member functions • Data hiding! Set/Get data member by member function of an object classClassName { private: intdataMember; public: voidmemberFunctionName() { // … } // … }; // change or set the value of data member objectName.setXXXXX( parameter ); // visit or get the value of data member varible = objectName.getXXXXX( );

  26. Lecture 14 • Chapter 16. Introduction to Class and Object • 16.1 Introduction • 16.2 Classes, Objects, Member Functions and Data Members • 16.3 Overview of the chapter examples • 16.4 Defining a class • 16.5 Defining a member function • 16.6 Data member • 16.7 Initializing object with constructors • 16.8 Separate file • 16.10 Validating data with set function

  27. 16.7 Initializing object with constructors • What is Initialization? • When creating objects, provide the initial values for data members • Why we need Initialization? • In real world, there are some attributes of each object given at the birth • In programming world, it is better to provide initial values for the variables • How can we do initialization? • Using Constructor(构造函数) functions • A special kind of function to achieve above goals • Function name is the class name • No return values!

  28. 16.7 Initializing object with constructors • Analyze the requirement User create its own gradebook Get the gradebook User can set the course name Get the course name Private data: Course name Open the gradebook Display the course name

  29. 16.7 Initializing object with constructors • Design the class in UML Class Name Data members Constructor Two functions are defined to set/get the private data Member functions

  30. Constructor function Set/get functions are atomic operations for data members, called by other functions

  31. Two objects of the same class are created with initial parameters

  32. Objects in Memory gradeBook_1 gradeBook_2 gradeBook_n Storage for data members (数据成员存储) courseName “CS101 Introduction to C++ Programming” Storage for data members (数据成员存储) courseName “CS102 Data Structures in C++” Storage for data members (数据成员存储) courseName “Other course names” ... Common function instruction entries (共用函数代码存储): GradeBook(), setCourseName(), getCourseName(), displayMessage(),... Scope of GradeBook Class in memory

  33. Experiment • 继续刚才的日期类 • 完成构造函数的设计 • 打印相应的测试信息

  34. Summary • Declaration of a Class with constructor • With constructor, it is easy to create multiple objects with different attributes classClassName { private: intdataMember; public: ClassName( data_typeinitial_parameters) { } voidmemberFunctionName() { // … } // … };

  35. Lecture 14 • Chapter 16. Introduction to Class and Object • 16.1 Introduction • 16.2 Classes, Objects, Member Functions and Data Members • 16.3 Overview of the chapter examples • 16.4 Defining a class • 16.5 Defining a member function • 16.6 Data member • 16.7 Initializing object with constructors • 16.8 Separate file • 16.10 Validating data with set function

  36. 16.8/16.9 Separate file • An engineering problem • When several programmers work together, the definition of variables and functions may be different, while the declaration part may be the same and will be shared • For example • Several programmers work on different functions of one class • One class will be used to create objects in another program • ...... • Solution • Divided the function definition part (called as implementation) from the declaration part (called as interface ) of the Class • In the software team • The role of system designer will handle the interfaces • The role of coding programmers will handle the implementation

  37. Header file • What can be write in the header file • The common “#include ...” • The declaration of shared Class definition • The declaration of global variables and functions • The individual definition of functions cannot be written in header file, such as “main() { }” • How can the source code find the header • It is always located at the same directory of the source code file, indicating by “header_file.h” • It can also be located at the system path of C++ standard library, indicating by <header_file.h>

  38. The common codes can be separated into different files Interfaces (function declarations) in header file, e.g., myFunction.h Implementation (function definitions) in new source file, e.g., myFunction.cpp Single source file e.g., try.cpp Non-common part in previous source file, e.g. try.cpp

  39. The separation of Interfaces and implementations Interfaces (class definitions) in header file, e.g., myClass.h Implementation (member function definitions) in new source file, e.g., myClass.cpp Single source file e.g., try.cpp New source file e.g., myTry.cpp

  40. 16.9 Teamwork diagram Focus on how to implement the class Focus on how to use the class Class file Header file Program file End-user enjoy his life Execute file

  41. Lecture 14 • Chapter 17. Classes: A Deeper Look, I • 17.1 Introduction • 17.2 Time Class Case Study • 17.3 Class Scope and Accessing Class Members • 17.4 Separating Interface from Implementation • 17.5 Access Functions and Utility Functions • 17.6 Time Class Case Study: Constructors with Default Arguments • 17.7 Destructors • 17.8 When Constructors and Destructors Are Called • 17.9 Time Class Case Study: A Subtle Trap Returning a Reference to a private Data Member • 17.10 Default Memberwise Assignment

  42. Class Sample: Time 采用#ifndef, #define, #endif的预编译处理指令避免某个头文件在编译时被include多次

  43. 本例中Time类的成员函数是在类定义之外 独立给出函数定义的,如果将函数定义放在类的定义中,编译系统可能将其作为内联函数inline function处理 从软件工程的角度,只有十分简单的、代码稳定、可以公开的成员函数才适合放到包含类定义的头文件中去 本例中,构造函数直接初始化基本数据类型的数据成员,然后再由setXXX函数接收数据和进行数据的合理性校验 由于成员函数共享访问类的数据成员,面向对象的函数往往比面向过程的函数需要更少的参数、代码更加简化

  44. 用户自定义的类也是一种数据类型,还可以创建类的数组、指针以及引用用户自定义的类也是一种数据类型,还可以创建类的数组、指针以及引用 面向对象编程中数据(数据成员)与方法(成员函数)都被集成到类中,类具备判断数据有效性的能力

  45. Experiment • 继续刚才的日期类 • 完成date.h, date.cpp, main.cpp • 为月和日数据加上检查的功能 • 测试你的类

  46. 面向对象的编程 vs. 面向过程的编程 面向对象的编程 面向过程的编程 函数的设计 类的设计 类的调用: 类的实例化获得对象 对象可以维持自身数 据,同时还有方法 函数的调用: 主调函数需要 维持数据

  47. Experiment • 继续刚才的日期类 • 完成date.h, date.cpp, main.cpp

  48. 谢谢! 刘威 副教授 互联网技术与工程研究中心 华中科技大学电子与信息工程系 电话:13986224922 Email: liuwei@hust.edu.cn 网址:http://itec.hust.edu.cn

More Related