Transcript 投影片 1
C/C++ Basics (V)
Structures and Classes
Berlin Chen 2003
Textbook: 1. Walter Savitch, “Absolute C++,” Addison Wesley, 2002 開發代理
2. Walter Savitch, “Problem Solving With C++,” Addison Wesley, 2003
歐亞代理
Learning Objectives
• Structures (結構)
– Structure types
– Structures as function arguments
– Initializing structures
• Classes (類別)
– Defining, member functions
– Public and private members
– Accessor and mutator functions
– Constructors: definitions and calling
• Structures vs. classes
2
Structures
• 2nd aggregate data type: struct
• Recall: aggregate meaning ‘grouping’
– Recall array: collection of values of same
type
– Structure: collection of values of different
types
• Treated as a single item, like arrays
• Major difference: Must first ‘define’ struct
– Prior to declaring any variables
3
Structure Types
• Define struct globally (typically)
• No memory is allocated
• Just a ‘placeholder’ for what our struct
will ‘look like’
• Definition:
struct CDAccountV1 //Name of new struct ‘type’
{
double balance; //member names
double interestRate;
int
term;
};
Remember this semicolon!
4
Structure Types
• Keyword struct begins a structure
definition
• CDAccount is the structure tag or the
structure’s type
• Member names are identifiers declared in
the braces
5
Declare Structure Variable
• With structure type defined, now declare
variables of this new type:
CDAccountV1 account;
– Just like declaring simple types
– Variable account now of type CDAccountV1
– It contains ‘member values’
• Each of the struct ‘parts’
6
Accessing Structure Members
• Dot operator to access members
account.balance
account.interestRate
account.term
• Called ‘member variables’
– The ‘parts’ of the structure variable
– Different structs can have same name
member variables
• No conflicts
不同的結構可以有相同的成員變數名稱
7
Structure Example
See P225
先定義所將使用的結構 (structure)為何
以結構變數為參數傳遞
在這裡使用call-by-reference
原因為何?
8
Structure Example
以結構變數為參數的函數呼叫
9
Structure Example
10
Structure Example
11
Structure Pitfall
• Semicolon after structure definition
• “;” MUST exist
struct WeatherData
{
double temperature;
double windVelocity;
};
Remember this semicolon!
• Required since you ‘can’ declare structure
variables in this location
我們可以在定義結構時,同時宣告結構變數
12
Structure Assignments
• Given structure named CropYield
• Declare two structure variables:
CropYield apples, oranges;
– Both are variables of ‘struct type CropYield’
– Simple assignments are legal:
apples = oranges;
• Simply copies each member variable from apples
into member variables from oranges
13
Structures as Function Arguments
• Passed like any simple data type
– Pass-by-value
– Pass-by-reference
– Or combination
• Can also be returned by function
– Return-type is structure type
– Return statement in function definition
sends structure variable back to caller
14
Structures as Function Arguments
• Structures can be the type of a value returned by
a function
– Example:
CDAccount shrink_wrap(double the_balance,
double the_rate, int the_term)
{
CDAccount temp;
temp.balance = the_balance;
temp.interest_rate = the_rate;
temp.term = the_term;
return temp;
}
CDAccount new_account;
new_account = shrink_wrap(1000.00, 5.1, 11);
15
Initializing Structures
• Can initialize at declaration
• Example:
struct Date
{
int month;
int day;
int year;
};
Date dueDate = {12, 31, 2003};
• Declaration provides initial data to all three
member variables
16
Classes
• Similar to structures
– Adds member FUNCTIONS (成員函數)
– Not just member data/variables (成員資料/變數)
• Integral to object-oriented programming
– Focus on objects
• Object: Contains data and operations
• In C++, variables of class type are objects
– Or the values of variables of class type are
called objects
宣告為類別(class)資料型態的變數(variable)就稱為物件(object)
17
Class Definitions
• Defined similar to structures
• Example: 類別(class)的定義
class DayOfYear // name of new class type
{
public: // the access specifier
void output(); //member function(成員函數)
int month; //member data(成員資料)
int day;//member data(成員資料)
};
• Notice only member function’s prototype
(declaration)
• Function’s implementation is elsewhere
18
Declaring Objects
• Declared same as all variables
– Predefined types, structure types
• Example:
DayOfYear today, birthday;
• Declares two objects of class type DayOfYear
• Objects include:
– Data
• Members: month, day
– Operations (member functions)
• output()
19
Class Member Access
• Members accessed same as structures
• Example:
today.month
today.day
– And to access member function:
today.output(); //Invokes member function
20
Class Member Functions
• Must define or ‘implement’ class member
functions
• Like other function definitions
– Can be after main() definition
– Must specify class:
void DayOfYear::output()
{…}
• :: is scope resolution operator (範疇解析運算子)
• Instructs compiler ‘what class’ member is from
• Item before :: called type qualifier (類別限定)
21
Class Member Functions Definition
• Notice output() member function’s
definition (in next example)
• Refers to member data of class
– No qualifiers
today.month=12;
month=12;
(dot operators)
• Function used for all objects of the class
– Will refer to ‘that object’s’ data when invoked
– Example:
today.output();
• Displays ‘today’ object’s data
22
Class Member Functions Definition
DayOfYear today;
month (12, today.month)
day (31, today.day)
每一個新建立的類別物件都會有自己的
內部變數即類別成員的儲存空間
但同一類別的所有物件
會共用相同的一組類別
成員函數
DayOfYear birthday;
month (3, brithday.month)
day (28, brithday.day)
每一個新建立的類別物件都會有自己的
內部變數即類別成員的儲存空間
DayOfYear::output()
No dot operator !
{
cout<<“month =”<<month
<<“day=”<<day<<endl;
}
23
Complete Class Example
See P237
24
Complete Class Example
25
Dot and Scope Resolution Operator
• Used to specify ‘of what thing’ they are
members
• Dot operator
– Specifies member of particular object
– Used with an object of that class
• Scope resolution operator
today.month=12;
today.output();
– Specifies what class the function definition
comes from
– Used with a class name
26
A Class’s Place
• Class is full-fledged type!
– Just like data types int, double, etc.
• Can have variables of a class type
– We simply call them ‘objects’
• Can have parameters of a class type
– Pass-by-value
– Pass-by-reference
• Can use class type like any other type!
27
Encapsulation (資料封裝)
• Any data type includes
Information Hiding
or Data Abstraction
– Data (range of data)
– Operations (that can be performed on data)
• Example:
int data type has:
Data: -32,768 ~ +32,767
Operations: +,-,*,/,%, logical,
predefined library functions, etc.
• Same with classes (programmer-defined types)
– But WE specify data, and the operations to
be allowed on our data!
28
Abstract Data Types (抽象資料型態)
• ‘Abstract’
– Programmers don’t know details of how the
values and operations are implemented
• Abbreviated ‘ADT’
– Collection of data values together with set
of basic operations defined for the values
• ADT’s often ‘language-independent’
– We implement ADT’s in C++ with classes
• C++ class ‘defines’ the ADT
– Other languages implement ADT’s as well
29
More Encapsulation
• Encapsulation
– Means ‘bringing together as one’
• Declare a class get an object
• Object is ‘encapsulation’ of
– Data values
– Operations on the data (member functions)
A programmer who uses a class should
not need to even look at the definitions of
the member functions.
30
Principles of OOP
• Information Hiding
– Details of how operations work not known
to ‘user’ of class
(programmer)
• Data Abstraction
– Details of how data is manipulated within
ADT/class not known to user
• Encapsulation
– Bring together data and operations, but
keep ‘details’ hidden
31
Public and Private Members
• Data in class almost always designated
private in definition!
– Upholds principles of OOP
– Hide data from user
– Allow manipulation only via operations
• Which are member functions
– Within the definitions of member functions
• Public items (usually most member
functions) are ‘user-accessible’
32
Public and Private Example
• Modify previous example:
class DayOfYear
{
public:
void input();
void output();
private:
int month;
int day;
};
Access specifiers
• Data now private
• Objects have no direct access
33
Public and Private Example 2
• Given previous example
– Declare object:
DayOfYear today;
– Object today can ONLY access public
members
cin >> today.month; // NOT ALLOWED!
cout << today.day; // NOT ALLOWED!
– Must instead call public operations:
today.input();
today.output();
34
Public and Private Example 2
• See P244, Display 6.4
35
Public and Private Style
• Can mix & match public & private
• More typically place public first
– Allows easy viewing of portions that can be
USED by programmers using the class
– Private data is ‘hidden’, so irrelevant to users
• Outside of class definition, cannot change
(or even access) private data
36
Accessor and Mutator Functions
• Object needs to ‘do something’ with it’s
data, called
• Accessor member functions
– Allow object to read data
– Also called ‘get member functions’
– Simple retrieval of member data
• Mutator member functions
– Allow object to change data
– Manipulated based on application
37
Separate Interface and
Implementation
• User of class need not see details of how
class is implemented
– Principle of OOP encapsulation
• User only needs ‘rules’
– Called ‘interface’ for the class
• In C++ public member functions and
associated comments
• Implementation of class hidden
– Member function definitions elsewhere
– User needs not see them
38
Constructors
• Initialization of objects (e.g. class variables)
– Initialize some or all member variables
– Other actions possible as well
• A special kind of member function
– Automatically called when object declared
• Very useful tool
– Key principle of OOP
39
Constructor Definitions
• Constructors defined like any member
function, except that:
1. Must have same name as class
2. Cannot return a value; not even void!
3. Automatically called when object declared
40
Constructor Definition Example
• Class definition with constructor:
class DayOfYear
{
public:
DayOfYear(int monthValue, int dayValue);
//Constructor initializes month & day
void input();
void output();
…
private:
int month;
int day;
}
41
Constructor Notes
• Notice name of constructor: DayOfYear
– Same name as class itself!
• Constructor declaration has no return-type
– Not even void !
• Constructor in public section
– It’s called when objects are declared
– If private, could never declare objects!
• Would make the class completely useless
42
Calling Constructors
• Declare objects:
DayOfYear date1(7, 4), date2(5, 5);
– Objects are created here
– Constructor is called
• Values in parentheses passed as arguments to
constructor
– Member variables month, day initialized:
date1.month 7
date2.month 5
date1.dat 4
date2.day 5
43
Constructor Equivalency
• Consider:
DayOfYear date1, date2
date1.DayOfYear(7, 4); // ILLEGAL!
date2.DayOfYear(5, 5); // ILLEGAL!
– Seemingly OK…
– CANNOT call constructors like other member
functions! (A special kind of member function!)
DayOfYear date1(7, 4), date2(5, 5);
44
Constructor Code/Definition
• Constructor definition is like all other
member functions:
DayOfYear::DayOfYear(int monthValue, int dayValue)
{
month = monthValue;
day = dayValue;
}
– Note same name around :: (type qualifier)
– Clearly identifies a constructor
– Note no return type
– Just as in class definition
45
Alternative Definition
• Previous definition equivalent to:
DayOfYear::DayOfYear( int monthValue, int dayValue)
: month(monthValue), day(dayValue)
{…}
– Second line called ‘Initialization Section’
– Body left empty (not always!)
– Preferable definition version
46
Constructor Additional Purpose
• Not just initialize data
• Body doesn’t have to be empty
– In initializer version
• Validate the data!
– Ensure only appropriate data
is assigned to class private
member variables
– Powerful OOP principle
47
Overloaded Constructors
• Can overload constructors just like other
functions
• Recall: a signature of function consists of:
– Name of function
– Parameter list
• Provide constructors for all possible
argument-lists
– Particularly ‘how many’
48
Class with Constructors Example
See Page 269
49
Class with Constructors Example
50
Class with Constructors Example
51
Constructor with No Arguments
• Can be confusing
• Standard functions with no arguments:
– Called with syntax: callMyFunction();
• Including empty parentheses
• Object declarations with no ‘initializers’:
DayOfYear date1;
DayOfYear date();
// This way!
// NO!
– What is this really?
– Compiler sees a function declaration/prototype!
• Yes! Look closely!
52
Explicit Constructor Calls
• Can also call constructor AGAIN
– After object declared
• Recall: constructor was automatically called then
– Can call via class’s name; standard member
function call
• Convenient method of setting member
variables
• Method quite different from standard
member function call
53
Explicit Constructor Call Example
• Such a call returns ‘anonymous object’
– Which can then be assigned
– In Action:
DayOfYear holiday(7, 4);
• Constructor called at object’s declaration
• Now to ‘re-initialize’:
holiday = DayOfYear(5, 5);
– Explicit constructor call
– Returns new ‘anonymous object’
– Assigned back to current object
54
Explicit Constructor Call Example
•
Explicit default constructor call
holiday = DayOfYear();
– The parentheses are only omitted when you
declare a variable of the class type and want
to invoke a constructor with no arguments
as part of the declaration
DayOfYear holiday;
55
Default Constructor
• Defined as: a constructor with no arguments
• One should always be defined
• Auto-Generated?
– Yes & No
• If no constructors AT ALL are defined Yes
• If any constructors are defined No
• If no default constructor:
– Cannot declare: MyClass myObject;
• With no initializers
如果在類別定義中已有宣告其他
constructors 時,在物件宣告時
就不能如此使用!
56
Class Type Member Variables
• Class member variables can be any type
– Including objects of other classes!
– Type of class relationship
• Powerful OOP principle
• Need special notation for constructors
– So they can call ‘back’ to member object’s
constructor
57
Class Member Variable Example
See P275
58
Class Member Variable Example
Invoke a constructor from the
class DayofYear
See P275
59
Parameter Passing Methods
• Efficiency of parameter passing
– Call-by-value
• Requires copy be made Overhead !
– Call-by-reference
• Placeholder for actual argument
• Most efficient method
• Negligible difference between these two methods
for simple types
• For class types clear advantage
• Call-by-reference desirable
– Especially for ‘large’ data, like class types
60
The const Parameter Modifier
• Large data types (typically classes)
– Desirable to use pass-by-reference
– Even if function will not make modifications
• Protect argument
– Use constant parameter
• Also called constant call-by-reference parameter
• Place keyword const before type
– Makes parameter ‘read-only’
– Attempts to modify result in compiler error
61
The const Parameter Modifier
But, some modification
should be made for this
member function.
Constant parameters are a form of automatic error checking. When an
inadvertent change to the constant parameters occurring, the compiler
will issue an error message.
62
The const Modifier for
Class Member function
• Use the const modifier to tell the compiler
that a member function invocation should
not change the member variables of calling
object
– The const goes at the end of the function
declaration
class BankAccount
{
public:
……
void output() const;
…...
}
void BankAccount::output() const
{
…...
}
The const goes at the end of
function declaration and function heading
63
The const Modifier for
Class Member function
• Pitfall: Inconsistent Use of const
– If you do not add the const modifier to the
function declaration for the member function
output, the function welcome will produce an
error message
64
Inline Functions (內嵌函數)
• For non-member functions:
– Use keyword inline in function declaration
and function heading
• For class member functions:
– Place implementation (code) for function IN
class definition automatically inline
• Use for very short functions only
• Code actually inserted in place of call
– Eliminates overhead of function invocations
– More efficient, but only when short!
65
Inline Member Functions
• Member function definitions
– Typically defined separately, in different file
– Can be defined IN class definition
• Makes function ‘in-line’
• Have the disadvantage of mixing the interface and
implementation of a class and go against the
principle of encapsulation
• Again: use for very short functions only
• More efficient
– If too long actually less efficient!
66
Inline Member Functions
67
static Members
• Static member variables
– All objects of class ‘share’ one copy
– One object changes it
all see change
– Must be initialized outside the
class definition, and can’t be
initialized more than once
• Useful for ‘tracking’
– How often a member function is called
– How many objects exist at given time
• Place keyword static before type
68
static Functions
• Member functions can be static
– If no access to object data needed
– And still ‘must’ be member of the class
– Make it a static function
• Can then be called outside class
– From non-class objects:
• E.g.: Server::getTurn();
Using the class name and
scope resolution operator
– As well as via class objects
• Standard method: myObject.getTurn();
• Can only use static (member) data,
functions!
69
static Members
1
3
2
70
Structures versus Classes
• Structures
– Typically all members public
– No member functions
• Classes
– Typically all data members private
– Interface member functions public
• Technically, same
– Perceptionally, very different mechanisms
71
Thinking Objects
• Focus for programming changes
– Before algorithms center stage
– OOP data is focus
• Algorithms still exist
– They simply focus on their data
– Are ‘made’ to ‘fit’ the data
• Designing software solution
– Define variety of objects and how they
interact
72
Summary 1
• Structure is collection of different types
• Class used to combine data and functions
into single unit object
• Member variables and member functions
– Can be public accessed outside class
– Can be private accessed only in a member
function’s definition
• Class and structure types can be formal
parameters to functions
73
Summary 2
• C++ class definition
– Should separate two key parts
• Interface: what user needs
• Implementation: details of how class works
• Constructors: automatic initialization of
class data
– Called when objects are declared
– Constructor has same name as class
• Default constructor has no parameters
– Should always be defined
74
Summary 3
• Class member variables
– Can be objects of other classes
• Require initialization-section
• Constant call-by-reference parameters
– More efficient than call-by-value
• Can inline very short function definitions
– Can improve efficiency
• Static member variables
– Shared by all objects of a class
– Can be accessed by static member functions
75