1 Chapter 9 Objects and Classes C/C++ Language Programming Wanxiang Che.
-
Upload
randell-kennedy -
Category
Documents
-
view
229 -
download
0
Transcript of 1 Chapter 9 Objects and Classes C/C++ Language Programming Wanxiang Che.
1
Chapter 9 Objects and Classes
C/C++ Language Programming
Wanxiang Che
Outline
• OOP Concepts
• Class & Object
• Friend Class and Function
• Operator Overloading
2
3
OO Programming Concepts
• Object-oriented programming (OOP) involves programming using objects
• Object– An entity in the real world that can be distinctly
identified– A student, a desk, a circle, a button, and even a loan
• An object has a unique identity, state, and behaviors– State: a set of data fields (properties) with their
current values– Behavior: a set of functions
名人名言• 对象提供一种处理复杂性问题的方式,这个问题可以追溯到亚里士多德:您把这个世界视为过程还是对象?在面向对象兴起运动之前,编程以过程为主,例如结构化设计方法。然而,系统已经到达了超越其处理能力的复杂性极点。有了对象,我们能够通过提升抽象级别来构建更大的、更复杂的系统—我认为,这才是面向对象编程运动的真正胜利。
---- Grady Booch (UML创始人之一 )
4
5
Classes
• Constructs that define objects of the same type
• Using variables to define data fields
• Functions to define behaviors
6
Objects
An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.
Class Name: Circle Data Fields:
radius is _______ Functions:
getArea
Circle Object 1 Data Fields:
radius is 10
Circle Object 2 Data Fields:
radius is 25
Circle Object 3 Data Fields:
radius is 125
A class template
Three objects of the Circle class
7
Classes class Circle { public: // The radius of this circle double radius; // Construct a circle object Circle() { radius = 1; } // Construct a circle object Circle(double newRadius) { radius = newRadius; } // Return the area of this circle double getArea() { return radius * radius * 3.14159; } };
Data field
Function
Constructors
8
Constructors
• Constructors must have the same name as the class itself.
• Constructors do not have a return type—not even void.
• Constructors play the role of initializing objects.
9
Constructing without Arguments
A constructor is invoked when an object is created. The syntax to create an object using the no-arg constructor is:
ClassName variableName;
e.g.
Circle circle1;
10
Constructing with Arguments
To declare an object using a constructor with arguments is
ClassName variableName(arguments);
e.g.
Circle circle2(5.5);
11
Access Operator
After an object is created, its data can be accessed and its functions invoked using the dot operator (.), also known as the object member access operator:
objectName.dataField references a data field in the object.
objectName.function(arguments) invokes a function on the object.
12
A Simple Circle Class
• Objective: Demonstrate creating objects, accessing data, and using functions.
13
Class is a Type
You can use primitive data types to define variables. You can also use class names to declare object names. In this sense, a class is also a data type.
14
Memberwise Copy
Use the assignment operator = to copy the contents from one object to the other. By default, each data field of one object is copied to its counterpart in the other object. For example,
circle2 = circle1;
copies the radius in circle1 to circle2. After the copy, circle1 and circle2 are still two different objects, but with the same radius.
15
Class Replaces struct
The C language has the struct type for representing records. For example, you may define a struct type for representing students as shown in (a).
struct Student
{ int id;
char firstName[30];
char mi;
char lastName[30];
};
(a)
class Student
{ public:
int id;
char firstName[30];
char mi;
char lastName[30];
};
(b)
Accessing Object Members via Pointers
Circle circle1;
Circle *pCircle = &circle1;
cout << "The radius is " << (*pCircle).radius << endl;
cout << "The area is " << (*pCircle).getArea() << endl;
(*pCircle).radius = 5.5;
cout << "The radius is " << pCircle->radius << endl;
cout << "The area is " << pCircle->getArea() << endl;
16
17
Data Field Encapsulation The data fields radius in the Circle class can be modified directly (e.g., circle1.radius = 5). This is not a good practice for two reasons:
• Data may be tampered. • Makes the class difficult to maintain and vulnerable
to bugs
18
Accessor and Mutator Colloquially, a get function is referred to as a getter (or accessor), and a set function is referred to as a setter (or mutator).A get function has the following signature:
returnType getPropertyName()
If the returnType is bool, the get function should be defined as follows by convention:
bool isPropertyName()
A set function has the following signature:void setPropertyName(dataType propertyValue)
19
Example: New Circle Class
Circle
-radius: double
+Circle()
+Circle(radius: double)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double
The radius of this circle (default: 1.0).
Constructs a default circle object.
Constructs a circle object with the specified radius.
Returns the radius of this circle.
Sets a new radius for this circle.
Returns the area of this circle.
The - sign indicates private modifier
20
Passing Objects to Functions You can pass objects by value, by reference, or by pointer.
c: Circle
radius: 5.0
myCircle: Circle radius: 5.0
Copy myCircle to c
myCircle: Circle
radius: 5.0
c is an alias for myCircle
myCircle: Circle radius: 5.0
c:
address of myCircle
21
Array of ObjectsCircle circleArray[3] = {Circle(3), Circle(4), Circle(5)};int main() { // Create a Circle object with radius 1 Circle circleArray[3] = {Circle(3), Circle(4), Circle(5)}; for (int i = 0; i < 3; i++) { circleArray[i].setRadius(i + 1); } cout << "The total areas of circles is \t" << sum(circleArray, 3) << endl;}
double sum(Circle circleArray[], int size) { double sum = 0;
// Add areas to sum for (int i = 0; i < size; i++) sum += circleArray[i].get_area();
return sum;}
22
The C++ string Class
string
+string()
+string(value: string)
+string(value: char[])
+string(ch: char, n: int)
+append(s: string): string
+append(s: string, index: int, n: int): string
+append(s: char[], n: int): string
+append(n: int, ch: char): string
+assign(s: char[]): string
+assign(s: string, index: int, n: int): string
+assign(s: string, n: int): string
+assign(n: int, ch: char): string
+at(index: int): char
+length(): int
+size(): int
+capacity(): int
+clear(): void
+erase(index: int, n: int): string
+empty(): bool
+compare(s: string): int
+compare(index: int, n: int, s: string): int
+copy(s: char[], index: int, n: int): void
+data(): char[]
+substr(index: int, n: int): string
+substr(index: int): string
+swap(s: string): void
+find(ch: char): int
+find(ch: char, index: int): int
+find(s: string): int
+find(s: string, index: int): int
+replace(index: int, n: int, s: string): string
+insert(index: int, s: string): string
+insert(index: int, n: int, ch: char): string
Constructs an empty string.
Constructs a string with the specified string literal value.
Constructs a string with the specified character array.
Constructs a string initialized with the specified character n times.
Appends string s into this string object.
Appends n number of characters in s starting at the position index to this string.
Appends the first n number of characters in s to this string.
Appends n copies of character ch to this string.
Assigns array of characters or a string s to this string.
Assigns n number of characters in s starting at the position index to this string.
Assigns the first n number of characters in s to this string.
Assigns n copies of character ch to this string.
Returns the character at the position index from this string.
Returns the number of characters in this string.
Same as length().
Returns the size of the storage allocated for this string.
Removes all characters in this string.
Removes n characters from this string starting at position index.
Returns true if this string is empty.
This two compare functions are like the strcmp function in §7.9.4, “String Functions,” with the same return value.
Copies n characters into s starting at position index.
Returns a character array from this string.
Returns a substring of n characters from this starting at position index.
Returns a substring of this string starting at position index.
Swaps this string with s.
Returns the position of the first matching character for ch.
Returns the position of the first matching character for ch at or from the position index.
Returns the position of the first matching substring s.
Returns the position of the first matching substring s starting at or from the position index.
Replaces the n characters starting at position index in this string with the string s.
Inserts the string s into this string at position index.
Inserts the character ch n times into this string at position index.
How to use string?
• Constructing a String– string str; string str(“Hello”);
• Assigning a String– str.assign(“Harbin”); str.assign(4, 'G');
• Appending a String– str.append(" World!");
• = + > < …– string str1;
– str1 = str;
– str1 = str + “ World!”
– str > “World” ? 23
Implement MyString Class
class MyString {
private:
char* p;
public:MyString();~MyString();MyString(const char*);MyString& assign(const char*);
MyString& append(const char*);
const char* c_str() const;
};
24
How to implement = + > < …?
25
26
Operator Overloading
• Programmer can use some operator symbols to define special member functions of a class
• Provides convenient notations for object behaviors
27
int i, j, k; // integers
float m, n, p; // floats
k = i + j;
// integer addition and assignment
p = m + n;
// floating addition and assignment
Operator Overloading
The compiler overloads the + operator for built-in integer and float types by default.
We can make object operation look like individual int variable operation, using operator functions
MyString a,b,c;c = a + b;
28
Operator Overloading Syntax
• Syntax is:
operator@(argument-list)
--- operator@ is a function
--- @ is one of C++ operator symbols (+, -, =, etc..)
Examples:
operator+
operator-
operator*
operator/
= Function Operator
• MyString & operator=(const MyString&);
• Why we need overload = operator?
• str1 = str2 is OK?– Let me try …
29
+= Function Operator
• MyString & operator+=(const MyString&);
30
31
Friend Functions and Classes
Private members of a class cannot be accessed from outside of the class. Occasionally, it is convenient to allow some trusted functions and classes to access a class’s private members. C++ enables you to use the friend keyword to declare friend functions and friend classes for a class so these functions and classes can access the class’s private members.
32
Friend Classesclass Date{public: friend class Student;private: int year; int month; int day;};
class Student{public: void p() { birth_date.year = 2000; cout << birth_date.year; }private: Date birth_date;};int main(){ Student s; s.p(); return 0;}
33
Friend Functionsclass Date { friend void p();private: int year; int month; int day;};void p() { Date date; date.year = 2000; cout << date.year;}int main() { p(); return 0;}
34
+ Function Operator
friend MyString operator+(const MyString& ls, const MyString& rs);
35
Overloading the << and >> Operators
• In fact, cout<< or cin>> are operator overloading built in C++ standard lib of iostream, using operator "<<" and ">>"
• cout and cin are the objects of ostream and istream classes, respectively
• We can add a friend function which overloads the operator << or >>
Overloading the << Operators
friend ostream & operator<<(ostream &os, MyString &s)
{
os << s.p;return os;
}
36
面向对象的好处• 话说东汉末年,曹操有一天大宴席群臣,曹操喝地兴起,突然诗性大发:“喝酒唱歌,人生真爽……”,众文武齐呼:“丞相好诗!!”,于是就有一些比较爱拍马的人叫工匠速速印刷,让全天下人都知道这首好诗。于是工匠马上开始动手 (写代码 )。
37
人工书写• string a,b,c;
• a = "喝酒唱歌,人生真爽 ";
• b = "喝酒唱歌,人生真爽 ";
• c = "喝酒唱歌,人生真爽 ";
• cout << a << endl;
• cout << b << endl;
• cout << c << endl;
38
刻板印刷• string a,b,c;
• a = "对酒当歌,人生真爽 ";
• b = a;
• c = b;
• cout << a << endl;
• cout << b << endl;
• cout << c << endl;
39
活字印刷class Word {
private: string word; string font;public: void SetWord(string word); string GetWord(); void SetWordFont(string font);};
int main() { Word word[] = new Word[9]; word[0].SetWord(“ 对” ); word[0].SetWordFont(“黑体” ); word[1].SetWord(“ 酒” ); word[2].SetWord(“ 当” ); word[2].SetWordFont(“斜体” ); word[3].SetWord(“ 歌” );
…… for (int i = 0; i < 9; ++i) { cout << word[i].GetWord(); }}
40
面向对象体现的好处• 可维护• 可复用• 可扩展
41