1 Object oriented programming What is Class? What is Object? - From object-oriented point of view - Class is a user-defined data type which contains relevant.

Slides:



Advertisements
Similar presentations
C Program Design Supplements 主講人:虞台文. Content Who takes the return value of main() ?
Advertisements

CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
File streams Chapter , ,
Introduction to Java Programming Lecture 13 Classes I OO Programming.
程式註解說明. 2 程式註解格式 塊狀註解 對檔案、 class 、 method 、資料結構、一段程式 …. 等程式區塊 做說明。 第一行的開頭必需為 “/*” 且沒有其他文字,最後一行的開頭 必需以 “*/” 做為結束,在中間每一行的開頭都必需是一個 “*” 。 單行註解 佔據一整行的說明。 以.
Introduction to Java Programming Lecture 5: Using Java Classes : String & Math Spring 2009.
Introduction to pointers in C/C++. Pointers 特殊變數 存放變數在記憶體中的位址 MinGW C++ 中佔用 4 bytes 間接定址取執法 位址 指標變數 變數內容 變數.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
Hung-Hsiang WuWindows Processing Design1 Chapter 3 基本觀念 變數宣告與型態 特殊運算子符號 字串與數值的轉換 類別與物件的觀念 建立新的專案 WinMain 程式進入點 Include Header File.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
SECTION 2 C++ Language Basics. Strategies for learning C++ Focus on concepts and programming techniques. (Don’t get lost in language features) Learn C++
資料結構實習-一 參數傳遞.
計算機概論實習 Integral Stream Base expression: dec, oct, hex, setbase, and showbase Use header Integers normally base 10 (decimal) Stream manipulators.
Windows Processing Design1 Chapter 1 C/C++ 概論 畫面輸出與鍵盤輸入 程式流程 程式流程的迴圈 函數的基礎 指標與陣列 字串 類別 利用 BCB 開發程式.
Stream i/o C++ default i/o class. Template classcharacter based class wide-character based class basic_ios basic_ios ios ios wios wios basic_istream basic_istream.
Introduction to Java Programming Lecture 12 Method Benefits, Declaring, and Calling Methods.
Visual C++重點複習.
I/O of C and C++. printf and scanf of C Should add printf (“control string”, exp1, exp2,…) Scanf(“control string”, &var1, &var2,…)
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
C++ Programming Certificate University of Washington Cliff Green
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
Functions Why we use functions C library functions Creating our own functions.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
計算機程式語言 Lecture 03-1 國立臺灣大學生物機電系 3 3 Assignment, Formatting, and Interactive Input.
C++ Streams Lecture-2.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Streams, Files, and Formatting Chapter Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams.
Data Structures (1st Exam). 1.[5] Suppose there are only two constructors for a class, one that passes in a single integer parameter called amount, for.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
I/O and Data Formatting Introduction to Class Concepts INFSY 307 Spring 2003 Lecture 3.
Copyright 2008 Oxford Consulting, Ltd 1 October C to C++ C++ Comments Can use the symbol // To identify single line comments.
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
1 Simple Input/Output  C++ offers the iostream library, which defines a system of character-oriented Input/Output (I/O) using object oriented programming.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1436 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
SEI PowerPoint Presentation for LiuHui, Object-Oriented Programming for C++, 2 nd Edition Copyright 2007 © SEI, All rights reserved Object-Oriented.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
CS116 SENEM KUMOVA METİN. Outline What is C++ ? Some features of C++ Input and Output Operations Manipulators C++ header files Namespaces and scope resolution.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 13: Exam 1 Preview.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
C++ Programming Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Introduction to C++ (Extensions to C)
Lecture 9 Files, Pointers
Standard Input/Output Streams
Standard Input/Output Streams
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Chapter 3 Input output.
Speaker: Liu Yu-Jiun Date: 2009/4/15
CPS120: Introduction to Computer Science
Instructor: Dr. Michael Geiger Spring 2019 Lecture 13: Exam 1 Preview
Presentation transcript:

1 Object oriented programming What is Class? What is Object? - From object-oriented point of view - Class is a user-defined data type which contains relevant data and functions - Object is a variable declared under some class data type - From philosophy concept - Class is an abstract concept that describes the attributes of a collection of objects

2 From C to C++ Namespace - 變數、函數、或物件所屬的空間名稱, 在不同的 namespace 中可使用相同的變數名稱。 - std: C++ 所有系統提供的函數所屬的 namespace - avoid conflict of variable names in the different class libraries

3 namespace example //This program outputs the message // //C++:one small step for the program, //one giant leap for the programmer // //to the screen #include using namespace std; int main(){ cout <<"C++:one small step for the program,\n" <<"one giant leap for the programmer \n"; return 0; } compare to C: #include main( ){ printf(“….”); without namespace

4 namespaces create namespace - examples: namespace mfc{ int inflag; void g(int); … } namespace owl{ int inflag; … }

5 namespace use variables in a namespace - use scope resolution operator :: - e.g. mfc::inflag = 3; owl::inflg = -823; cout << mfc::inflag; the using directive - e.g.. using namespace mfc; inflag = 3; // 相當於 mfc::inflag = 3; owl::inflag = -823;

6 C++ Input/Output C++ Input/Output objects - cin standard input - coutstandard output - cerrstandard error - e.g. cin >> x; cin >> len; cout << x; cout << len; cin >> x >> len; cout << x << len;

7 C++ Input/Output example #include using namespace std; int main( ) { int id; float av; cout << “Enter the id and the average:”; cin >> id >> av; cout << “Id:” << id << ‘\n’ << “Average:” << av << ‘\n’; return 0; } Enter the id and the average: Id: Average:90.8

8 C++ Input Output Manipulators - for the format of I/O - set width to n: setw(n) for (i=1; i<=1000; i*=10) cout << setw(6) << i << ‘\n’;

9 manipulators endl: end of line, write new line - e.g. int i=4, j=6, k=8; char c=‘!’; cout << i << c << endl << j << c <<‘\n’ << k << c << endl; 4! 6! 8!

10 manipulators oct (octal), hex(hexadecimal), dec(decimal) - e.g. int i = 91; cout << “i=“ << i << “ (decimal)\n”; cout << “i=“ << oct << i << “ (octal)\n”; cout << “i=“ << hex << i << “ (hexadecimal)\n”; cout << “i=“ << dec << i << “ (decimal)\n”; i=91 (decimal) i=133 (octal) i=5b (hexadecimal) i=91 (decimal)

11 manipulators listed in Figure dec, endl, fixed, flush, hex, left, oct, right, scientific, setfill( c ), setprecision(n), setw(n), showpoint, noshowpoint, showpos, noshowpos, skipws, noskipws, ws -

12 manipulators setfill, setprecision - e.g. float a = 1.05, b=10.15, c=200.87; cout << setfill(‘  ’) << setprecision(2); cout << setw(10) << a << ‘\n’; cout << setw(10) << b << ‘\n’; cout << setw(10) << c << ‘\n’; ******1.05 *****10.15 ****200.87

13 files (example) #include using namespace std; const int cutoff =6000; const float rate1 =0.3; const float rate2 =0.6; int main(){ ifstream infile; ofstream outfile; int income,tax; infile.open("income.txt"); outfile.open("tax.txt"); while (infile >>income ){ if (income <cutoff ) tax =rate1 *income; else tax =rate2 *income; outfile<<"Income="<<income <<"greenbacks \n" <<"Tax ="<<tax <<"greenbacks \n"; } infile.close(); outfile.close(); return 0; }

14 files (example cont.) input file “income.txt” result: output file “tax.txt” Income = 2214 greenbacks Tax= 664 greenbacks Income = greenbacks Tax= 6299 greenba cks Income = greenbacks Income = greenbacks

15 files testing whether files are open - file object converts to ‘true’ if open successfully, otherwise converts to ‘false - e.g. ifstream infile; ifstream.open(“scores.dat”); … if (infile) { … } // if open sucessfully or if (!infile) { … } // if fail to open the file

16 files - e.g.. ifstream infile; infile.open(“scores.dat”); if (!infile) { cerr << “Unable to open scores.dat\n”; exit(0); }

17 C++ features bool data type - values: true (1) or false(0) - manipulators: boolalpha, noboolalpha (default) - e.g. bool flag; flag = (3 < 5); cout << flag << ‘\n’; cout << boolalpha << flag << ‘\n’; 1 true

18 the type string string initialization - e.g. #include string s1; string s2 = “Bravo”; string s3 = s2; string s4(10,’x’); cout << s1 << ‘\n’; cout << s2 << ‘\n’; cout << s4 << ‘\n’; Bravo xxxxxxxxxx

19 the type string C-style string (end with a null char ‘\0’) char  mystring = “a string”; or char mystring[ ] = “a string”; printf(“%s\n”, mystring); char mystring[9] - the null character ‘\0’ is added by the C compiler automatically a s t r i n g \0

20 the type string string length string s = “Ed Wood”; cout << “Length=“ << s.length( ) << ‘\n’; input a string - separate by space or new line cout << “Enter a string:”; cin >> s; cout << s; Length=7 Ed Wood Ed

21 getline function example (copy file) #include using namespace std; int main(){ string buff; ifstream infile; ofstream outfile; cout << “Input file name:”; cin >> buff; infile.open(buff.c_str()); cout << “Output file name:”; cin >> buff; outfile.open(buff.c_str()); while (getline(inflie, buff)) outfile <<buff<<“\n\n”; infile.close(); outfile.close(); return 0; }

22 the type string input a line of string from cin stirng s; getline(cin, s); concatenation of string string s1=“Atlas ”, s2=“King”, s3; s3 = s1 + s2; cout << s1 << ‘\n’; cout << s2 << ‘\n’; cout << s3 << ‘\n’; Atlas King Atlas King

23 the type string remove a substring - s.erase(position, length); - e.g. string s = “Ray Dennis Steckler”; s.erase(4, 7); cout << s << ‘\n’; Ray Steckler

24 the type string insert a string - s.insert(position, str2); replace a substring - s.replace(startpos, length, str2); swap strings - s1.swap(s2); extract a substring - s.substr(position, length)

25 the type string [ ] operator string s = “Nan” cout << s[1]; << ‘\n’; s[0] = ‘J’; cout << s << ‘\n’; search a substring - s1.find(s2, position); compare strings - ==, !=,, = a Jan

26 functions reference variables - provides an alternative name for storage - e.g. memory int x; int& ref=x; x ref x = 3; cout << ref; 3

27 functions call by value (default in C) - pass values to the called function call by reference - pass addresses to the called function - provided in C++, but not in C - e.g. void swap(int&, int&);

28 call by reference #include using namespace std; void swap(int&, int&); int main( ) { int i=7, j=-3; swap(i, j); cout << “i=“ << i << ‘\n’ << “j=“ << j << ‘\n’; return 0; } void swap(int& a, int& b) { int t; t=a; a=b; b=t; } pass address of i, j to a,b main( ) swap( ) t i a j b 7 -3 i=-3 j=7

29 call by reference in C (use pointer) #include void swap(int*, int*); // function prototype main( ) { int i=7, j=-3; swap(&i, &j); // passing addresses of i and j printf(“i=%d j=%d”, i,j); } void swap(int* a, int* b) { // use pointers parameters instead int t; // of reference variables t = *a; *a = *b; *b=t; // use pointers to reference the } // values in main function

30 functions default arguments - all the parameters without default values must come first in the parameter list. - better to specify in the prototype, e.g. void f(int val, float s=12.6, char t=‘\n’, string msg=“Error”); - valid invocation f(14, 48.3, ‘\t’, “ok”); // s=48.3, t=‘\t’, msg=“ok” f(14, 48.3); // s=48.3, t=‘\n’, msg=“Error” f(14); // s=12.6, t=‘\n’, msg=“Error”

31 functions overloading functions - functions can have the same name, but - function signatures need to be distinct - function name - number, data type, and order of it arguments - e.g. void print(int a); void print(double a); // o.k. void print(int a, int b); // o.k. int print(int a); // wrong! return type is not part of signatures

32 overloading functions #include void print(int a); void print(double a); int main( ){ int x=8; double y=8.0; print(x); print(y); return 0; } void print(int a) { cout << a << ‘\n’; } void print(double a) { cout << showpoint << a <<‘\n’; }

33 dynamic (vs. static)allocation dynamic allocation - pointer_var = new data-type; // single data - pointer_var = new data-type[size]; // array - e.g. int* int_ptr; int_ptr = new int; ptr int* ptr; ptr = new int[100]; ptr[0] ptr[1] … ptr[99] …

34 dynamic allocation delete, delete[ ] - free storage allocated by new or new type[size] - e.g. delete int_ptr; delete[ ] ptr; linked list example name next start ‧‧‧ “ 林旺 ”“ 馬蘭 ”“ 阿美 ” 0

35 dynamic allocation #include using namespace std; struct Elephant { string name; Elephant* next; }; void print_elephants(const Elephant* ptr ); Elephant* get_elephants( ); void free_list(const Elephant* ptr ); int main( ) { Elephant* start; start =get_elephants( ); print_elephants(start ); free_list(start ); return 0; }

36 dynamic allocation Elephant* get_elephants( ){ Elephant *current,*first; int response; current =first =new Elephant; cout <<"\nNAME:"; cin >>current ->name; cout <<"\nAdd another?(1 ==yes, 0 ==no):"; cin >>response; //Add Elephants to list until user signals halt. while (response ==1 ){ current =current ->next =new Elephant; cout <<"\nNAME:"; cin >>current ->name; cout <<"\nAdd another?(1 ==yes, 0 ==no):"; cin >>response; } current ->next =0; return first; }

37 dynamic allocation void print_elephants(const Elephant* ptr ){ int count =1; cout <<"\n \n \n"; while (ptr !=0 ){ cout <<"Elephant number“ <<count++ name <<’\n ’; ptr =ptr ->next; } void free_list(const Elephant* ptr ){ const Elephant* temp_ptr; while (ptr !=0 ){ temp_ptr =ptr ->next; delete ptr; ptr =temp_ptr; }

38 dynamic allocation struct Elephant { string name; Elephant* next; }; first current current - >name current - >next Elephant * start; … Elephant *current,*first; current =first =new Elephant; current =current ->next =new Elephant;

39 exception handling try-throw-catch clause try { … // regular statements throw an_exception; … } catch (exception1) { … } // exception handlers catch (exception2) { … } …

40 exception handling example int* ptr; try { ptr = new int; // throw bad_alloc exception if ‘new’ failure … } catch (bad_alloc) { cerr << “new: unable to allocate storage!\n”; exit(0); } …

41 homework #2 (1). 執行課本 Example 的程式 (p.71), 輸入至少 10 隻象的名字。 (2). 加入一新的 function 名為 reverse_elephant 至 Example2.7.1 中, 其 function prototype 如下 : Elephant* reverse_elephant(Elephant* start); 此 function 的功能在於建立一新 linked list, 將原以 start 為起點的 linked list 中的資料做反向連結, 然後傳回此新的 linked list 的起始 位置的 pointer 值 ;並在 main function 中至少重複呼叫 reverse_function 兩次, 用以驗證你的程式的正確性。例如 : 原 : start … 經 reverse_elephant 後 : rstart … elp1elp2elpn 0 elpnelp2elp1 0