16.5 Defining a member function

advertisement
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
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
-2-
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
-3-
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
-4-
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
Your car, attributes
My car, attributes Different attributes when implementing
{ VW Polo, Sliver, 80000km }
{ Toyota, Red, 100000km }
-5-
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, …}
-6-
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
Data members
Member functions
Private:
…
Protected:
…
Public:
…
Private:
…
Protected:
…
Public:
…
-7-
Summary

Object-oriented programming
 Class and object



It is data-centered (以数据为中心,信息封装,信息隐藏)



Class describes the attributes and the methods
An object is an instance of the class, which can be visited by program
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
“How much money?”
“Access Denied”
“How many boxes?”
“Three”
Public
accessible
-8-
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
-9-
16.3 Grades book

Grades book

(教师成绩簿)
Used to record the
grades of students in
one class

One sample page of real grade book
-10-
16.4 Defining Class

Analyze requirement
Open the gradebook
Display welcome message

Design the class in UML
Class Name
Data members(None)
Public accessible
Member functions
-11-
16.4 Defining Class
Class Definition
(类的定义)
创建类的一个对象
ClassName myObjectName;
访问对象的一个成员函数
myObjectName.MemberFunction();
-12-
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,
成员访问说明符
public + 冒号
myObjectName, myFunctionName
Definition of a member
function (成员函数的定义)
-13-
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
-14-
16.5 Defining a member function

Analyze requirement
Open the gradebook
Display the course name
as user want

Design the class in UML
Class Name
Data members(None)
Public accessible
Member functions
-15-
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
-16-
16.5 Defining a member function
Enable the string library
#include <string>
Member Function with
input parameter
-17-
Temporally string
variable
getline(cin,stringObject)
从cin输入流获取stringObject
-18-
Summary

Definition of a Class with member functions
class ClassName
{
public:
void memberFunctionName()
{
// …
}
};

Create a object instance of the class, class is also a
type! // create an object
ClassName myObjectName;

Calling
// the
callmember
object's function
function of an object
myObjectName.myFunctionName();
-19-
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
-20-
16.6 Data member

Analyze requirement
User input the course name
Get the course name
Open the gradebook
Private data:
Course name
Display the course name

Design the class in UML
Private accessible
Class Name
Data members
Two functions are
defined to set/get
the private data
Member functions
-21-
16.6 Data member
Member functions:
public access
Data member:
private access
Set/get functions are atomic
operations for data members,
called by other functions
Declaration of
data member
-22-
Call member
function to get
data member
Call member
function to set
data member
Call member
function to show
data member
-23-
Experiment

设计一个日期类


包括月、日信息作为数据成员
打印一条提示信息“date is xx-xx”
-24-
Summary

Declaration of a Class with data members
class ClassName
{
private:
int dataMember;
public:
void memberFunctionName()
{
// …
}
// …
};


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
// change or set the value of data member
objectName.setXXXXX( parameter );
// visit or get the value of data member
varible = objectName.getXXXXX( );
-25-
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
-26-
16.7 Initializing object with constructors

What is Initialization?


Why we need Initialization?



When creating objects, provide the initial values for data
members
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!
-27-
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
16.7 Initializing object with constructors

Design the class in UML
Class Name
Constructor
Two functions are
defined to set/get
the private data
Data members
Member functions
-29-
Constructor
function
Set/get functions are atomic
operations for data members,
called by other functions
-30-
Two objects of the same class are
created with initial parameters
-31-
Objects in Memory
gradeBook_1
gradeBook_2
gradeBook_n
Storage for
data members
(数据成员存储)
Storage for
data members
(数据成员存储)
Storage for
data members
(数据成员存储)
courseName
courseName
“CS101 Introduction
to C++
Programming”
...
“CS102 Data
Structures in C++”
courseName
“Other course
names”
Common function instruction entries (共用函数代码存储):
GradeBook(), setCourseName(),
getCourseName(), displayMessage(),...
Scope of GradeBook Class in memory
-32-
Experiment

继续刚才的日期类


完成构造函数的设计
打印相应的测试信息
-33-
Summary

Declaration of a Class with constructor
class ClassName
{
private:
int dataMember;
public:
ClassName( data_type initial_parameters)
{
}
void memberFunctionName()
{
// …
}
// …
};

With constructor, it is easy to create multiple objects with
different attributes
-34-
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
-35-
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
-36-
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>
-37-
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
-38-
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
-39-
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
-40-
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
-41-
Class Sample: Time
采用#ifndef, #define, #endif的预编译处理指
令避免某个头文件在编译时被include多次
本例中Time类的成员函数是在类定义之外
独立给出函数定义的,如果将函数定义放在
类的定义中,编译系统可能将其作为内联函
数inline function处理
从软件工程的角度,只有十分简单的、代码稳定、
可以公开的成员函数才适合放到包含类定义的头文
件中去
本例中,构造函数直接初始化基本
数据类型的数据成员,然后再由
setXXX函数接收数据和进行数据
的合理性校验
由于成员函数共享访问类的数据成员,面
向对象的函数往往比面向过程的函数需要
更少的参数、代码更加简化
用户自定义的类也是一种数据类型,
还可以创建类的数组、指针以及引用
面向对象编程中数据(数据成员)
与方法(成员函数)都被集成到类
中,类具备判断数据有效性的能力
Experiment

继续刚才的日期类



完成date.h, date.cpp, main.cpp
为月和日数据加上检查的功能
测试你的类
-45-
面向对象的编程 vs. 面向过程的编程
面向对象的编程
面向过程的编程
类的设计
类的调用:
类的实例化获得对象
对象可以维持自身数
据,同时还有方法
函数的设计
函数的调用:
主调函数需要
维持数据
-46-
Experiment

继续刚才的日期类

完成date.h, date.cpp, main.cpp
-47-
谢谢!
刘威 副教授
互联网技术与工程研究中心
华中科技大学电子与信息工程系
电话:13986224922
Email: liuwei@hust.edu.cn
网址:http://itec.hust.edu.cn
Download