Lập trình Hướng đối tượng những đối tượng, đó là các thực thể có mối công ty trình lấy đối tượng làm nền tảng để xây dựng thuật giải, xây dựng chương trình... Lập trình Hướng đối tượng L
Trang 1Cơ bản về hướng đối tượng và C++
Trang 2Tài liệu tham khảo
Công nghệ, ĐH Quốc gia HN
Công nghệ, ĐH Quốc gia HN
Trang 3Nội dung
Trang 4OOP Mục tiêu của kỹ sư phần mềm
Trang 5Độ phức tạp và độ lớn ngày
càng cao
biệt là chức năng thông minh
Trang 8Mục tiêu của việc thiết kế 1
phần mềm
phần có thể được sử dụng trong nhiều phần
Trang 10Lập trình không có cấu trúc
Trang 12nhỏ hay một nhóm công việc trong toàn bộ hệ thống
các chương trình con nhỏ hơn
Chương trình = Cấu trúc dữ liệu + Giải thuật
Trang 15thống trong thực tế
Trang 16Lập trình Hướng đối tượng
những đối tượng, đó là các thực thể có mối
công ty
trình lấy đối tượng làm nền tảng để xây dựng
thuật giải, xây dựng chương trình
Trang 17Lập trình Hướng đối tượng
Lập trình hướng đối tượng là phương pháp
và đối tượng (object)
Trang 18Lập trình Hướng đối tượng
3/3/2009 Lập trình
Hướng đối tượng 18
Trang 19OOP Một số khái niệm
hiểu như là một thực thể: người, vật hoặc một bảng dữ liệu….
Trang 21Đối tượng trong LTHĐT
Trang 22• Date objects, time objects, paycheck objects, invoice objects, audio objects, video objects, file objects, record objects, etc.
• Any noun can be represented as an object
easier to maintain than procedural programming
22 3/3/2009
Trang 23OOP Một số khái niệm
được gom chung lại thành lớp đối tượng Ví dụ Người là một lớp đối tượng Một lớp đối tượng
được đặc trưng bằng các thuộc tính, và các
hoạt động (hành vi, thao tác).
tượng, có giá trị nhất định cho mỗi đối tượng tại mỗi thời điểm trong hệ thống Vd: Tên, Tuổi, Cân nặng là các thuộc tính của Người
đối tượng tác động qua lại với các đối tượng khác hoặc với chính nó.
Trang 24OOP Một số khái niệm
tương ứng với một cài đặt cụ thể khác nhau.
Một cài đặt như vậy được gọi là một phương
thức (method).
áp dụng cho nhiều lớp đối tượng khác nhau,
một thao tác như vậy được gọi là có tính đa
hình (polymorphism).
một thể hiện (instance) của lớp đó.
Joe Smith, 25 tuổi, nặng 58kg, là một thể hiện của lớp người.
Trang 25Destructor
Constructor
Other public methods
Trang 26OOP Sơ đồ đối tượng
tượng Sơ đồ đối tượng bao gồm sơ đồ lớp và
sơ đồ thể hiện
thống, một lớp đối tượng được diễn tả bằng một hình chữ nhật có 3 phần:
tượng trong lớp đó
Trang 27OOP Sơ đồ lớp và sơ đồ thể hiện
Sinh viên Họ tên
Năm sinh Mã số
Điểm TB
Đi học
Đi thi Phân loại
(Sinh viên) Nguyễn Văn A 1984
0610234T 9.2
Tên lớp
Thuộc tính
Thao tác
Đối tượng = Dữ liệu + Phương thức
Trang 28Thiết kế theo hướng đối tượng
quan
động chuyên biệt
đối tượng cụ thể
Trang 29OOP Các đặc điểm quan trọng
Trang 31OOP Trừu tượng hóa
cách nhìn khái quát hóa về một tập các đối tượng có chung các đặc điểm được quan tâm (và bỏ qua những
chi tiết không cần thiết).3/3/2009 31
Trang 32OOP Đóng gói – Che dấu thông tin
vào làm một, để sau này có thể dùng một cái tên
để gọi đến
thủ tục có liên quan
thông tin và chi tiết cài đặt nội bộ để bên ngoài không nhìn thấy
Trang 33và thao tác đó đã được định nghĩa tại lớp D.
tượng: đặc biệt hóa (“là”), khái quát hóa
Trang 35Các ưu điểm của OOP
trình an toàn không bị thay đổi bới những đoạn chương trình khác
Trang 36OOP có các đặc tính chủ
yếu sau
tả được đối tượng.
tượng được gắn với cấu trúc dữ liệu đó.
Trang 37OOP có các đặc tính chủ
yếu sau
nhau qua các hàm
đối tượng nào đó khi cần thiết
dưới lên (bottom-up).
Trang 38OOP Một số thuật ngữ
hướng đối tượng
OOM (Object Oriented Methodology): Phương pháp luận hướng đối tượng
OOA (Object Oriented Analysis): Phân tích
hướng đối tượng.
OOD: Object Oriented Design ( Thiết kế hướng đối tượng).
OOP: Object Oriented Programming ( lập trình hướng đối tượng).
Inheritance: Kế thừa
Polymorphism: Đa hình
Encapsulation: Tính đóng gói.
Trang 39Ngôn ngữ lập trình hướng đối tượng
hướng đối tượng
Trang 40OOP Lịch sử ngôn ngữ lập trình
Trang 42Program is created inthe editor and stored
on disk
Preprocessor programprocesses the code
Loader puts program
in memory
CPU takes eachinstruction andexecutes it, possiblystoring new datavalues as the programexecutes
Compiler
Compiler createsobject code and stores
it on disk
Linker links the objectcode with the libraries,creates a.out andstores it on disk
Editor Preprocessor
Linker
CPU
Primary Memory
.
.
.
.
Disk Disk Disk Disk
Disk
3/3/2009
Trang 44 cerr
• Standard error stream
44 3/3/2009
Trang 45C++
/* You can still use the old comment style, */
/* but you must be // very careful about mixing them */ // It's best to use this style for 1 line or partial lines /* And use this style when your comment
consists of multiple lines */
cout << "hey";
char name[10];
cin >> name;
cout << "Hey " << name << ", nice name." << endl;
cout << endl; // print a blank line
// declare a variable when you need it
for (int k = 1; k < 5; k++){
cout << k;
}
45 3/3/2009
Trang 47Preprocessor directive to include input/output stream header file
Stream insertion operator.
Keyword return is one
of several means to exit function; value 0 indicates program terminated
successfully.
Trang 488 int integer1; // first number to be input by user
9 int integer2; // second number to be input by user
10 int sum; // variable in which sum will be stored
11
12 cout << "Enter first integer\n" ; // prompt
13 cin >> integer1; // read an integer
14
15 cout << "Enter second integer\n" ; // prompt
16 cin >> integer2; // read an integer
24 } // end function main
Declare integer variables.
Use stream extraction operator with standard input stream to obtain user input.
Stream manipulator std::endl outputs a newline, then “flushes output buffer.”
Concatenating, chaining or cascading stream insertion operations.
Calculations can be performed in output statements:
alternative for lines 18 and 20:
std::cout << "Sum is " << integer1 + integer2 << std::endl;
Trang 528 void useLocal( void ); // function prototype
9 void useStaticLocal( void ); // function prototype
10 void useGlobal( void ); // function prototype
Local variable with function scope.
Create a new block, giving
x block scope When the block ends, this x is
destroyed.
Trang 5327
28 cout << "local x in main's outer scope is " << x << endl;
29
30 useLocal(); // useLocal has local x
31 useStaticLocal(); // useStaticLocal has static local x
32 useGlobal(); // useGlobal uses global x
33 useLocal(); // useLocal reinitializes its local x
34 useStaticLocal(); // static local x retains its prior value
35 useGlobal(); // global x also retains its value
Trang 54Phạm
vi biến
43 // useLocal reinitializes local variable x during each call
44 void useLocal( void )
45 {
46 int x = 25 ; // initialized each time useLocal is called
47
48 cout << endl << "local x is " << x
49 << " on entering useLocal" << endl;
Trang 55Phạm
vi biến
56 // useStaticLocal initializes static local variable x only the
57 // first time the function is called; value of x is saved
58 // between calls to this function
59 void useStaticLocal( void )
60 {
61 // initialized only first time useStaticLocal is called
62 static int x = 50 ;
63
64 cout << endl << "local static x is " << x
65 << " on entering useStaticLocal" << endl;
66 ++x;
67 cout << "local static x is " << x
68 << " on exiting useStaticLocal" << endl;
Trang 56Phạm
vi biến
72 // useGlobal modifies global variable x during each call
73 void useGlobal( void )
74 {
75 cout << endl << "global x is " << x
76 << " on entering useGlobal" << endl;
77 x *= 10 ;
78 cout << "global x is " << x
79 << " on exiting useGlobal" << endl;
80
81 } // end function useGlobal
local x in main's outer scope is 5
local x in main's inner scope is 7
local x in main's outer scope is 5
local x is 25 on entering useLocal
local x is 26 on exiting useLocal
local static x is 50 on entering useStaticLocal
local static x is 51 on exiting useStaticLocal
global x is 1 on entering useGlobal
global x is 10 on exiting useGlobal
This function does not declare any variables It uses the global x declared
in the beginning of the program.
Trang 57Phạm
vi biến
local x is 25 on entering useLocal
local x is 26 on exiting useLocal
local static x is 51 on entering useStaticLocal
local static x is 52 on exiting useStaticLocal
global x is 10 on entering useGlobal
global x is 100 on exiting useGlobal
local x in main is 5
Trang 58Unitary Scope Resolution
Operator
Trang 5917 // define local constant PI
18 const float PI = static_cast < float >( :: PI );
19
20 // display values of local and global PI constants
21 cout << setprecision( 20 )
22 << " Local float value of PI = " << PI
23 << "\nGlobal double value of PI = " << :: PI << endl;
24
25 return 0 ; // indicates successful termination
Access the global PI with ::PI
Cast the global PI to a float for the local PI This example will show the difference between float and double.
Trang 60Ví dụ
26
27 } // end main
Borland C++ command-line compiler output:
Local float value of PI = 3.141592741012573242
Global double value of PI = 3.141592653589790007
Microsoft Visual C++ compiler output:
Local float value of PI = 3.1415927410125732
Global double value of PI = 3.14159265358979
Trang 61OOP Tham chiếu
void swap1(int x, int y) { int t = x; x = y; y = t; }
void swap2(int *x, int *y) { int *t = x; x = y; y = t; }
void swap3(int &x, int &y) { int t = x; x = y; y = t; }
Trang 62Tham chiếu
62 3/3/2009
Trang 63Tham chiếu
Alias for argument in function call
Use & after data type in prototype
• void myFunction( int &data )
• Read “data is a reference to an int”
63 3/3/2009
Trang 649 int squareByValue( int ); // function prototype
10 void squareByReference( int & ); // function prototype
18 cout << "x = " << x << " before squareByValue\n" ;
19 cout << "Value returned by squareByValue: "
Trang 6531 // squareByValue multiplies number by itself, stores the
32 // result in number and returns the new value of number
33 int squareByValue( int number )
39 // squareByReference multiplies numberRef by itself and
40 // stores the result in the variable to which numberRef
41 // refers in function main
42 void squareByReference( int &numberRef )
Changes number, but original parameter (x) is not modified.
Changes numberRef, an alias for the original
parameter Thus, z is changed.
Trang 67Tham chiếu
int count = 1; // declare integer variable count Int &cRef = count; // create cRef as an alias for count ++cRef; // increment count (using its alias)
• Reference to undefined variable
67
3/3/2009
Trang 69Borland C++ command-line compiler error message:
Error E2304 Fig03_22.cpp 11: Reference variable 'y' must be
initialized in function main()
Microsoft Visual C++ compiler error message:
D:\cpphtp4_examples\ch03\Fig03_22.cpp(11) : error C2530: 'y' :
references must be initialized
Uninitialized reference – compiler error.
Trang 70OOP Chồng hàm (Functions overloading )
int abs(int i) { return abs(i);}
long abs(long l) { return labs(l);}
double abs(double d) { return fabs(d);}
void test_abs() {
long l = abs(-10l); // abs(long )
Trang 71• I.e., function to square ints and function to
int square( int x) {return x * x;}
float square(float x) { return x * x; }
71 3/3/2009
Trang 72Function Overloading
Trang 738 // function square for int values
9 int square( int x )
16 // function square for double values
17 double square( double y )
Trang 7424 int main()
25 {
26 int intResult = square( 7 ); // calls int version
27 double doubleResult = square( 7.5 ); // calls double version
28
29 cout << "\nThe square of integer 7 is " << intResult
30 << "\nThe square of double 7.5 is " << doubleResult
fig03_25.cpp output (1 of 1)
Called square with int argument: 7
Called square with double argument: 7.5
The square of integer 7 is 49
The square of double 7.5 is 56.25
The proper function is called based upon the argument (int or double).
Trang 751 // Fig 3.26: fig03_26.cpp
2 // Name mangling.
3
4 // function square for int values
5 int square( int x )
6 {
7 return x * x;
8 }
9
10 // function square for double values
11 double square( double y )
12 {
13 return y * y;
14 }
15
16 // function that receives arguments of types
17 // int, float, char and int *
18 void nothing1( int a, float b, char c, int *d )
Trang 7623 // function that receives arguments of types
24 // char, int, float * and double *
25 char *nothing2( char a, int b, float *c, double *d )
Trang 77OOP Tham số ngầm định trong lời gọi
hàm
Chú ý:
danh sách tham số, để tránh nhầm lẫn các giá trị.
báo trong khuôn mẫu hàm
void inc(int &a, int b = 1);
void inc(int &a, int b) {
Trang 78Default Arguments
defaults
• Can be constants, global variables, or function calls
int myFunction( int x = 1, int y = 2, int z = 3 );
Trang 798 // function prototype that specifies default arguments
9 int boxVolume( int length = 1 , int width = 1 , int height = 1 );
10
11 int main()
12 {
13 // no arguments use default values for all dimensions
14 cout << "The default box volume is: " << boxVolume();
15
16 // specify length; default width and height
17 cout << "\n\nThe volume of a box with length 10,\n"
18 << "width 1 and height 1 is: " << boxVolume( 10 );
19
20 // specify length and width; default height
21 cout << "\n\nThe volume of a box with length 10,\n"
22 << "width 5 and height 1 is: " << boxVolume( 10 , 5 );
Trang 8024 // specify all arguments
25 cout << "\n\nThe volume of a box with length 10,\n"
26 << "width 5 and height 2 is: " << boxVolume( 10 , 5 , 2 )
33 // function boxVolume calculates the volume of a box
34 int boxVolume( int length, int width, int height )
The default box volume is: 1
The volume of a box with length 10,
width 1 and height 1 is: 10
The volume of a box with length 10,
width 5 and height 1 is: 50
The volume of a box with length 10,
width 5 and height 2 is: 100
Trang 81OOP Toán tử quản lý bộ nhớ động
int *x;
x = new int; // x = (int*)malloc(sizeof(int)); char *y;
y = new char[100]; // y = (char*)malloc(100);
Trang 82Const
– const double PI = 3.14;
– const Date openDate(18,8,2003);
Trang 83Inline Functions
instead of making function call
• Reduce function-call overhead
Trang 841 // Fig 3.19: fig03_19.cpp
2 // Using an inline function to calculate.
3 // the volume of a cube.
10 // Definition of inline function cube Definition of function
11 // appears before function is called, so a function prototype
12 // is not required First line of function definition acts as