Lecture Object oriented programming - Lecture no 23

After you have read and studied this chapter, you should be able to: Write programs that are easily extensible and modifiable by applying polymorphism in program design; define reusable classes based on inheritance and abstract classes and abstract methods; differentiate the abstract classes and Java interfaces; define methods, using the protected modifier; parse strings, using a String Tokenizer object. | CSC241: Object Oriented Programming Lecture No 23 Previous Lecture Example program Copy initialization Assignment operator overloaded Memory efficient string class Today’s Lecture Efficient string class Resolve problem while deleting String objects Dynamic Type Information Cont. It’s more efficient to create a new class to store the count Each object of this class, which we call strCount, contains a count and also a pointer to the string Cont. main() { } S3 *psc: hello world :strcount count: *str: String s3 = “hello world.”; String(char* s) { psc = new strCount(s); } strCount(char* s) { int length = strlen(s); str = new char[length+1]; strcpy(str, s); count=1; } 1 cout count==1) delete psc; else, (psc->count)--; psc = ; (psc->count)++; } 1 ~strCount() { delete[] str; } 2 cout count==1) delete psc; else, (psc->count)--; psc = ; (psc->count)++; } 1 ~strCount() { delete[] str; } 2 cout count)++; } cout << “\ns2=”; (); s2= hello world. addr=7550 3 Go to program Note Why must the assignment operator in String worry about deletion? S1 = S2; S2 *psc: 7550 :strcount count: *str: 1 7550 S1 *psc: 8750 :strcount count: *str: 1 8750 650 hello world 650 975 Good morning 975 S3 *psc: 8750 2 1 7550 S3 = S1; 0 7550 Cont. String object on the left of the equal sign (s1=s2) was pointing at some strCount object (call it oldStrCnt) before the assignment. After the assignment s1 will be pointing to the object on the right of the equal sign. If there are now no String objects pointing to oldStrCnt, it should be deleted. Assignment operator Copy constructor this Pointer The member functions of every object have access to a sort of magic pointer named this, which points to the object itself. Thus any member function can find out the address of the object of which it

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.