1. Trang chủ
  2. » Thể loại khác

...C04. Class and Object.pdf

24 86 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG VỚI C++ Trang 14 §èi t−îng vµ líp (Class and Object) MỤC TIÊU CỦA BÀI NÀY GIÚP NGƯỜI HỌC  Phân tích được khái niệm đóng gói dữ liệu  Khai báo và sử dụng một lớp  Khai báo và sử dụng đối tượng.  Sử dụng hàm thiết lập và hàm huỷ bỏ  Khai báo và sử dụng hàm thiết lập sao chép  Vai trò của hàm thiết lập ngầm định A/ NHẮC LẠI LÝ THUYẾT Trong C++, tên cấu trúc là một kiểu dữ liệu không cần kèm theo từ khoá struct. Lớp cho phép người lập trình mô tả các đối tượng thực tế với các thuộc tính và hành vi. Trong C++ thường sử dụng từ khoá class để khai báo một lớp. Tên lớp là một kiểu dữ liệu dùng khi khai báo các đối tượng thược lớp(các thể hiện cụ thể của lớp). Thuộc tính của đối tượng trong một lớp được mô tả dưới dạng các biến thể hiện. Các hành vi là các hàm thành phần bên trong lớp. Có hai cách định nghĩa các hàm thành phần của một lớp; khi định nghĩa hàm thành phần bên ngoài khai báo lớp phải đặt trước tên hàm thành phần tên của lớp và toán tử “::” để phân biệt với các hàm tự do cùng tên. Chỉ nên định nghĩa hàm thành phần bên trong khai báo lớp khi nó không quá phức tạp để cho chương trình dễ đọc. Có thể khai báo và sử dụng các con trỏ đối tượng, tham chiếu đối tượng. Hai từ khoá public và private dùng để chỉ định thuộc tính truy nhập cho các thành phần( dữ liệu/hàm) khai báo bên trong lớp. Thành phần bên trong lớp được khai báo public có thể truy nhập từ mọi hàm khai báo một đối tượng thuộc lớp đó. Thành phần private trong một đối tượng chỉ có thể truy nhập được bởi các hàm thành phần của đối tượng hoặc các hàm thành phần của lớp dùng để tạo đối tượng(ở đây tính cả trường hợp đối tượng là tham số của hàm thành phần) Hai hàm thành phần đặc biệt của một lớp gọi là hàm thiết lập và hàm huỷ bỏ. Hàm thiết lập được gọi tự động(ngầm định) mỗi khi một đối tượng được tạo ra và hàm huỷ bỏ được gọi tự động khi đối tượng hết thời gian sử dụng. Hàm thiết lập có thuộc tính public, cùng tên với tên lớp nhưng không có giá trị trả về. Một lớp có ít nhất hai hàm thiết lập: hàm thiết lập sao chép ngầm định và hàm thiết lập do người lập trình thiết lập(nếu không mô tả tường minh thì đó là hàm thiết lập ngầm định). Hàm huỷ bỏ cũng có thuộc tính public, không tham số, không giá trị trả về và có tên bắt đầu bởi ~ theo sau là tên của lớp. Bên trong phạm vị lớp( định nghĩa của các hàm thành phần), các thành phần của lớp được gọi theo tên. Trường hợp có một đối tượng toàn cục cùng tên, muốn xác định đối tượng ấy phải sử dụng toán tử “::”. Lớp có thể chứa các thành phần dữ liệu là các đối tượng của lớp khác. Các đối tượng này phải được khởi tạo trước đối tượng tương ứng của lớp bao. Mỗi đối tượng có một con trỏ chỉ đến bản thân nó, ta gọi đó là con trỏ this. Con trỏ này có thể được sử dụng tường minh hoặc ngầm định để tham xác định các thành phần bên trong đối tượng. Thông thường người ta sử dụng this dưới dạng ngầm định. Hàm bạn của một lớp là hàm không thuộc lớp nhưng có quyền truy nhập tới các thành phần private của lớp. LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG VỚI C++ Trang 15 Khai báo bạn bề có thể khai báo bất kỳ chỗ nào trong khai báo lớp. B. MỘT SỐ LƯU Ý (Các lỗi thường gặp, một số thói quen lập trình tốt .)    Các lỗi thường gặp  Quên dấu “;” ở cuối khai báo lớp  Khởi tạo các thành phần giá trị trong khai báo lớp  Định nghĩa chồng một hàm thành phần bằng một hàm không thuộc lớp  Truy nhập đến các thành phần riêng của lớp từ bên ngoài phạm vi lớp  Khai báo giá trị N gôn ngữ C # T rần V ăn T èo tvteo@agu.edu.vn 01/06/2006 N g ôn n g ữ C # C hư ng 2: L p Đ ối tư ợ ng n n n n n n n n n Đ ịnh nghĩa lớ p T ạo đối tư ợ ng S dụng thành viên static H u ỷ đ ối tư ợ ng (d estru cto r) T ruyền thông số cho hàm N ạp chồng (overload) constructor C ác thuộc tính (property) C ác vùng m ục tin read -only C u ộc sống bên tro n g đ ố i tư ợ n g 01/06/2006 N g ôn n g ữ C # Đ ịnh nghĩa lớ p n Cú pháp: [attributes][access-modifiers] class identifier [:base-class] [class-body] n n n identifier: tên class base class: lớ p sở đư ợ c base kế thừ a class body: thân lớ p, class nằm dấu ngoặc nhọn {}, thành viên đư ợ c định nghĩa 01/06/2006 N g ôn n g ữ C # V í dụ public class CDate{ int Year; int Month; int Day; public CurDate(){ C onsole.W rite(“{0}-{1}-{2}”,D ay, M o n th , Y ear); } static void Main() { CDate d = new CDate(); d.CurDate(); } } 01/06/2006 N g ôn n g ữ C # T khoá dẫn truy xuất (Access Modifiers) n n n n p u b lic : truy cập từ bên ngồi p riv ate: truy cập bên p ro tected: bên thêm lớ p kế thừ a Ngồi enternal protected internal Withdraw( ) Withdraw( )  balance Deposit( ) 01/06/2006 balance Deposit( ) N g ôn n g ữ C # C ác tham số hàm n n C ác hàm có nhiều tham số đư ợ c T rong thân hàm , tham số hoạt động biến cục public class MyClass{ public void SomeMethod(int firstParam, float secondParam){ C onsole.W riteL ine(“C ác tham số nhận đư ợ c:{0},{1}”, firstParam, secondParam); } static void Main(){ int x = 5; float y = 3.5; MyClass mc = new MyClass(); mc.SomeMethod( x , y ); } N g ôn n g ữ C # }01/06/2006 T ạo đối tư ợ ng n n n n C ác kiểu liệu có sẳn C # (int, long… ) th u ộ c k iểu trị (value type) nên đư ợ c lư u n h củ a stack C òn nhữ ng đối tư ợ ng thuộc kiểu q u i ch iếu (reference type) nên đư ợ c lư u nhớ củ a h eap v đ ể sử dụng chúng phải dùng từ khóa new new V í dụ: C D ate d = n ew C D ate(); H àm khở i dự ng (co nstru cto r) B ộ k hở i gán (Initializers) Copy constructor T k hóa this this 01/06/2006 N g ôn n g ữ C # H àm khở i dự ng (constructor) n n Đ ợ c triệu gọi lú c n b ạn ch o th ể h iện m ộ t đ ố i tư ợ ng C o n structor phải đư ợ c định nghĩa • H oặc định nghĩa theo ý bạn • H oặc trình biên dịch tự định nghĩa đối tư ợ ng đư ợ c tạo khơng làm cả, biến thành viên đư ợ c khở i gán m ặc định: số nguyên  zero, chuổi  rổng, bool  false n M ột hàm constructor: • C ó tên tên lớ p • K hơng có trị trả về, có tham số ( cần ) • T hư ng có m odifier public 01/06/2006 N g ôn n g ữ C # V í dụ using System; public class CDate { int Year, Month, Day; public CDate(){} public CDate(System.DateTime dt){ Year = dt.Year; Month = dt.Month; Day = dt.Day; } public void DisplayCurDate(){ … … } } 01/06/2006 N g ôn n g ữ C # public class Tester { static void Main() { DateTime curDate = DateTime.Now; CDate dt = new CDate(curDate); dt DisplayCurDate(); } } B ộ khở i gán (Initializers) n n n K hở i gán biến thành viên initializer thay khở i gán hàm constructor N ếu khơng có initializer constructor gán giá trị m ặc định N ếu constructor có khở i gán lại biến giá trị m i chồng lắp lên 01/06/2006 using System; public class CDate { int Year=2006, Month, Day; public CDate(){} public CDate(System.DateTime dt){ Year = dt.Year; Month = dt.Month; Day = dt.Day; } … … … } N g ôn n g ữ C # 10 Copy Constructors n n T ạo m ột đối tư ợ ng m i cách ch ép biến từ m ột đ ố i tư ợ ng có sẵn k iểu liệu C h o phép khở i gán m ột class (struct) bằn g cách ch ép m ột thể khác cù n g kiểu liệu 01/06/2006 using System; public class CDate { int Year, Month, Day; public CDate(CDate d) { this.Year = d.Year; this.Month = d.Month; this.Day = d.Day; } } … … … CDate ddd = new CDate( dd ); N g ôn n g ữ C # 11 T khó a this n n L m ột thể h iện h àn h củ a m ột đ ối tư ợ ng C ó cách sử dụng: • Đ ịnh danh thành viên thể • L thơng số cho m ột hàm • D ùng indexer để xác định m ột phần tử m ảng (trình bày chư ng sau) 01/06/2006 private int hour;//thành viên public void SomeMethod (int hour) { this.hour = hour; } public void FirstMethod (OtherClass otherObj) { otherObj.SomeMethod( this ); } N g ôn n g ữ C # 12 S dụng thành viên static n C ác thuộc tính hàm m ộ t lớ p instance member static member member • Instan ce m em b er đ ợ c g ắn liền v i k iểu d ữ liệu • S tatic m em b er đ ợ c x em thàn h ph ần củ a lớ p • T ru y xu ất đ ến static m em b er th ì kh ơng cần p h ải k h b áo lớ p n n n n n n V í dụ: Button.SomeMethod() thay viết: B utton btn = new B utton(); btn.S om eM ethod(); C # khơng có hàm (biến) tồn cục (global), thay vào hàm (biến) static T riệu gọi hàm static static S dụng hàm static constructor constructor S dụng private constructor S dụng m ục tin (field) static 01/06/2006 N g ôn n g ữ C # 13 T riệu g ọ i h àm static n n Hàm static khơng có qui ch iếu this khơng có m ột thể (instance instance)) Các hàm static không th ể trự c tiếp truy xuất thành viên khơng static V ì m uốn truy static x u ất m ột hàm nonstatic nonstatic,, n ó p hải cho m ột instance đối tư ợ n g 01/06/2006 using System; public class ... The Life and Times of an Object First, let's recap what happens when you create and destroy an object. You create an object like this: TextBox message = new TextBox(); // TextBox is a reference type From your point of view, the new operation is atomic, but underneath, object creation is really a two-phase process. First, the new operation has to allocate some raw memory from the heap. You have no control over this phase of an object's creation. Second, the new operation has to convert the raw memory into an object; it has to initialize the object. You can control this phase this by using a constructor. NOTE C++ programmers should note that in C#, you cannot overload new to control allocation. When you have created an object, you can then access its members by using the dot operator. For example: message.Text = "People of Earth, your attention please"; You can make other reference variables refer to the same object: TextBox ref = message; How many references can you create to an object? As many as you want! The runtime has to keep track of all these references. If the variable message disappears (by going out of scope), other variables (such as ref) might still exist. Therefore, the lifetime of an object cannot be tied to a particular reference variable. An object can only be destroyed when all the references to it have disappeared. NOTE C++ programmers should note that C# does not have a delete operator. The runtime controls when an object is destroyed. Like object creation, object destruction is also a two-phase process. The two phases of destruction exactly mirror the two phases of creation. First, you have to perform some tidying up. You do this by writing a destructor. Second, the raw memory has to be given back to the heap; the memory that the object lived in has to be deallocated. Once again, you have no control over this phase. The process of destroying an object and returning memory back to the heap is known as garbage collection. Writing Destructors You can use a destructor to perform any tidying up required when an object is garbage collected. The syntax for writing a destructor is a tilde (~) followed by the name of the class. For example, here's a simple class that counts the number of live instances by incrementing a static count in the constructor and decrementing a static count in the destructor: class Tally { public Tally() { this.instanceCount++; } ~Tally() { this.instanceCount--; } public static int InstanceCount() { return this.instanceCount; } . private static int instanceCount = 0; } There are some very important restrictions that apply to destructors: • You cannot declare a destructor in a struct. A struct is a value type that lives on the stack and not the heap, so garbage collection does not apply. • struct Tally • { • ~Tally() { . } // compile-time error } • You cannot declare an access modifier (such as public) for a destructor. This is because you never call the destructor yourself—the garbage collector does. public ~Tally() { . } // compile-time error • You never declare a destructor with parameters, and it cannot take any parameters. Again, this is because you never call the destructor yourself. ~Tally(int parameter) { . } // Creating and Using a DataViewManager Object To create a DataViewManager, you use one of the following constructors: DataViewManager() DataViewManager(DataSet myDataSet) where myDataSet specifies the DataSet used by the DataViewManager object. This sets the DataSet property of the new DataViewManager object to myDataSet. Let's take a look at an example of creating and using a DataViewManager. Assume you have a DataSet named myDataSet, which contains a DataTable populated with rows from the Customers table. The following example creates a DataViewManager object named myDVM, passing myDataSet to the constructor: DataViewManager myDVM = new DataViewManager(myDataSet); The next example sets the Sort and RowFilter properties that will be used later when a DataView for the Customers DataTable is created: myDVM.DataViewSettings["Customers"].Sort = "CustomerID"; myDVM.DataViewSettings["Customers"].RowFilter = "Country = 'UK'"; N ote The previous code doesn't actually create a DataView; it merely sets the properties of any DataView created in the future that views rows from the Customers D ataTable. The following example actually creates a DataView by calling the CreateDataView() method of the myDVM DataViewManager, passing the customersDT DataTable to CreateDataView(): DataView customersDV = myDVM.CreateDataView(customersDT); The Sort and RowFilter properties of the customersDV DataView are set to CustomerID and Country = 'UK' respectively. These are the same settings as those set earlier in the DataViewSettings property. Listing 13.4A shows a complete example that creates and uses the DataViewManager shown in this section. Listing 13.4A: USINGDATAVIEWMANAGER.CS /* UsingDataViewManager.cs illustrates the use of a DataViewManager object */ using System; using System.Data; using System.Data.SqlClient; class UsingDataViewManager { public static void Main() { SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" ); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT CustomerID, CompanyName, Country " + "FROM Customers"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet, "Customers"); mySqlConnection.Close(); DataTable customersDT = myDataSet.Tables["Customers"]; // create a DataViewManager object named myDVM DataViewManager myDVM = new DataViewManager(myDataSet); // set the Sort and RowFilter properties for the Customers DataTable myDVM.DataViewSettings["Customers"].Sort = "CustomerID"; myDVM.DataViewSettings["Customers"].RowFilter = "Country = 'UK'"; // display the DataViewSettingCollectionString property of myDVM Console.WriteLine("myDVM.DataViewSettingCollectionString = " + myDVM.DataViewSettingCollectionString + "\n"); // call the CreateDataView() method of myDVM to create a DataView Object-Oriented Database Systems: Promises, Reality, and Future Won Kim UniSQL, Inc. 9390 Research Blvd. Austin, Texas 78759 Abstract During the past decade, object-oriented technology has found its way into programming languages, user interfaces, databases, operating systems, expert systems, etc. Products labeled as object-oriented database systems have been in the market for several years, and vendors of relational database systems are now declaring that they will extend their products with object-oriented capabilities. A few vendors are now offering database systems that combine relational and object-oriented capabilities in one database system. Despite these activities, there are still many myths and much confusion about object-oriented database systems, relational systems extended with object-oriented capabilities, and even the necessities of such systems among users, trade journals, and even vendors. The objective of lhis paper is to review the promises of object-oriented database systems, examine the reality, and how their promises may be fulfilled through unification with the relational technology. 1. Definitions Object-oriented tcchnologics in use today include object-oriented programming languages (e.g., C++ and Smalltalk), object-oriented database systems, object-oriented user interfaces (e.g., Macintosh and Microsoft window systems, Frame and Interleaf desktop publishing systems), etc. An object-oriented technology is a technology that makes available to the users facilities that are based on “object-oriented concepts”. To define “object-oriented concepts”, we must first understand what an “object” is. The term “object” means a combination of “data” and “program” that represent some real-world entity. For example, consider an employee named Tom; Tom is 25 years old, and his salary is $25,000. Then Tom may be represented in a computer program as an object. The “data” part of this Permisrion to copy without fee all or part of thir materio/ ir granted provided that the copier are not made ot distributed JOT direct coynmercial advantage, the VLDB copyright notice and the title of the publication and itr date appear, and notice ir given that copying ia by permiskon of the Very Large Data Bare En- dowment. To copy oiherwiee, or to republish, rcqminr a Jee and/or special pemiwion from the Endowment. Proceedinga of the 19th VLDB Conbrence Dublin, Ireland 1993 object would be (name: Tom, age: 25, salary: $25,000). l’hc “program” part of the object may be a collc4Xion of programs (hire, retrieve the data, change age, change salary, fire). ‘I’hc data part consists of data of any type. For the “Tom” object, string is used for the name, intcgcr for age, and monetary for salary; but in general, cvcn any uscr-dcfincd type. such ;LV Employee, may be used. In the “Tom” object, the name, age, and salary arc called attributes of the object. Often, an object is said to“cncapsulatc”data and program. This means that the users cannot SIX the inside of the ohjcct “capsule”. but can use the object by calling the program part of the object. This is not much diffcrcnt from proccdurc UIIS in conventional programming; the users call a prwcthm hy supplying values for input paramctcrs and rcccivc rcsulL\; in output pwamctcfs. The term “object-oricntcd” roughly m&s a wu~hiaation of object encapsulation and inhcritancc. ‘I’hc l~‘rll1 “inhcritancc” is sometimes called “rcusc”. Inhcri~~~ncc III~WU roughly that a new object may bc crcalctl by cxlcndiug an existing object. Now Ict us understand the term “inhcritnncc” more precisely. An object has a data part and a program part. All objects Lập trình hướng đối tượng Bài 3: Đối tượng lớp Nội dung  Đối tượng  Lớp  Phép gán đối tượng  Thiết lập hủy bỏ  Dữ liệu hàm tĩnh  Hằng số  Hàm bạn lớp bạn Đối tượng Object = Data + Method Point object { // data int x,y; //method void init (int ox, int oy); void move (int dx, int dy); void display(); }; Lớp  Khai báo lớp class { private: public: }; #include #include class point{ private: int x,y; public: void init(int ox, int oy); void move(int dx, int dy); void display(); }; // Define component function outside declaration void point::init(int ox, int oy){ cout[...]... ” ... [attributes][access-modifiers] class identifier [:base -class] [class- body] n n n identifier: tên class base class: lớ p sở đư ợ c base kế thừ a class body: thân lớ p, class nằm dấu ngoặc nhọn {},... ợ n g 01/06/2006 using System; public class MyClass { public void SomeMethod(){ … … … } } public class Tester { static void Main() { MyClass mc = new MyClass(); mc.SomeMethod(); } } N g ôn n... ợ c triệu gọi trư c k h i b ất thể using System; public class MyClass củ a lớ p đư ợ c tạo { n n private static string Name; static MyClass() { N am e = “N am e”; } Khơng có access modifier K

Ngày đăng: 05/11/2017, 03:38

w