owned this note
owned this note
Published
Linked with GitHub
---
robots: index, follow
tags: NCTU, CS, 共筆, OOP, 游逸平
description: 交大資工課程學習筆記
lang: zh-tw
dir: ltr
breaks: true
disqus: calee
GA: UA-100433652-1
---
物件導向程式設計--游逸平
=====
`NCTU` `CS` `course`
[回主頁](https://hackmd.io/s/ByOm-sFue)
## Course
### pointer and reference
- const pointer
```C++
int const *ptr == const int *ptr
int *const ptr
const int *ptr == int const *ptr
```
Is it legal?
1.
```C++
const char *a = ...;
char *b = ...;
a = b; // yes
b = a; // in C yes but with warning that pointer from char*->const char* (type difference)
// no in C++, you must: b = (char*)a;
```
2.
```C++
char *const a = ...;
char *b = ...;
a = b; // no (pointer a is const)
b = a; // yes
```
- array and pointer
```C++
int b[5];
int *bptr = b;
bptr == &b[0] == b;
b[4] == *(bptr+4) == *(b+4);
```
* arithmetic
++, -- , +, +=, -, -=, ptr - ptr
```C++
int *v = ...;
v += 1 == v++; (v + 1*sizeof(int) )
ptr1-ptr2 == (length between ptr1 and ptr2) / sizeof(*ptr)
const char *suit[4] = {"hearts", "diamonds", "clubs", "spades"}
-> suit[0] = "hearts" (suit[0] is a pointer point to h's memory space)
```
- Dynamic memory management (ch 11.8)
* provide indirect addressing
* space can be dynamically created (heap) <-> declare value is in stack !
- C: malloc() and free()
- Cpp: new and delete
```C++
pointer = new data_type; // new int;
pointer = new data_type(initial_value); // new char('a');
delete pointer;
```
ex1:
```C++
int *pointer = new int(10)
if(!pointer)
cout << "poiner is NULL" << endl;
...
```
ex2:
```C++
int size;
int *array = new int[size]; // malloc(size * sizeof(int));
delete [] array;
```
ex3:
```C++
int rows = 4, columns = 5;
int **matrix = new int*[rows];
matrix[3][2]...;
```
- Function Pointers
* A function name is also a function pointer, such as array
ex:
```C++
void fun1(char *str) {
cout << str << endl;
}
void fun2(char *xtr) {
cout << str << endl;
}
void (*fn)(char*);
fn = fun1;
(*fn)( "Called first" );
fn - fun2;
(*fn)( "Called second" );
```
- Overall
pointer can point to: variable, pointer variable, function, but not reference
### stream I/O
- Introducton
* type-safe
* user-defined (overloading '<<' and '>>')
* streams - sequences of bytes -> much slower than cpu
* High-level/formatted
- bytes are grouped into meaningful units
- satisfactory for most I/O other than high-volume file processing
* Low-level/unformatted
- Individual bytes
- high-speed, high-volume
- harder to program
* header file
- iostream: cin, cout, cerr, clog (provide both unformatted and formatted)
- iomanip: setw, setprecision (performing formatted)
- fstream: (user-controlled file processing)
* iostream objects
- istream object
- cin
- ostream object
- cout, cerr (unbuffered), clog (buffered-faster)
- Formatted I/O
* easier for read
* Output
- standard
* char*
```C++
char *word = "again";
cout << word << endl; // again
char *word = "again";
cout << (void*)word << endl; // C-style
cout << static_cast<void*>(word) << endl; //C++-style
```
* ostream & put(char c);
return reference
```C++
cout.put('A').put('a').put(65).put('\n'); //AaA
```
* istream cin
- stream extraction operator (overloaded >> operator)
- when reference retruned by >> is used as a condition, void* cast operatior is implicitly invoked
- cin.get();
* returns char any char(including ' ', '\n', 'EOF'...
* EOF is constant(int)
* cin.eof() check EOF (C-z in Windows, C-d in Unix)
* istream& get(char* s, int n, char delim - '\n');
* will left '\n'
ex:
```C++
char ch1, ch2;
cin.get(ch1).get(ch2);
char buffer[80];
cin.get(buffer,80);
cin.get(buffer,80,',');
```
- cin.getline();
* istream& getline (char* s, streamsize n, char delim );
* .=. cin.get(buffer,80,','); but , will not left ',' //
- cin.ignore();
* istream& ignore (streamsize n = 1, int delim = EOF);
- cin.putback();
* istream& putback (char c);
* put back to pipe
- cin.peek();
* int peek();
* just see, won't get (cin.peek('A'); )
* type-safe, overloading
- Unformatted I/O
* faster
* Input
- read
* istream& read(char* s, int n);
* read byte
- gcount
* int gcount() const; (const 代表不會改到 object)
* reports number of bytes
* Output
- write
* ostream& write (const char* s, int n);
* 一個byte一個byte的輸出
- More
* iomanip
- setbase manipulator
- 改進位(dec, oct, hex)
* sticky(保留狀態)
- showbase
* sticky(保留狀態)
- setprecision(4) (float 精準度) == cout.precision(4)
* sticky(保留狀態)
- setw == cin.width() == cout.width()
* ostream: at most
* istream: at least
* non sticky
- left, right (向左、右對齊)
- Internal
- showpose (顯示狀態(+-))
- cout.fill( '*' ) (將剩下的以 ' * '填滿)
- cout.flags(), ios::fmtflags() (紀錄輸出格式, 刪除上面的格式)
- fixed
- cout.setf(), cout.unsetf(); (不會刪除上面的格式)
ex:
```C++
cout << number << "hex is: " << hex << showbase() << number;
cout << setprecision(3) << flo_num; // cout.precision(3) << flo_num;
cin >> setw(5) >> buffer; // cin.width(5) >> buffer;
cout << setw(2) << buffer; // cout.width(2) << buffer;
```
* Allows define own stream
```C++
ostream& tab(ostream& outjput) {
return output << '\t';
}
int main() {
cout << "User-defined" << tab << "manipulator" << endl;
return 0;
}
cout.flags(ios::showpos | ios::showpoint);
cout.setf(ios::);
cout.unset();
```
- Stream Error State
* goodbit: good()
* eofbit: eof()
* failbit: fail()
* badbit: fail(), bad()
ex:
```C++
void print_state() {
cout << "cin state good() = " << cin.good() <<< "eof()= " << cin.eod() << "fail()=" << cin.fail() << " bad()= " << cin.bad() << endl;
```
### Object-Oriented Programming (Classes and Objects) (PIE)
- What's OOP?
- What's Objects and CLasses
- Classes (Abstract Data Types)
* Overview
* Time Class
* member functions
* memberwise assignment operation
* passing and returning objects
- Procedural program => Passive data
- Object-oriented program => Active data
- Object and Class
* attribute values
* share same attributes form class
* define classes -> create objects
* object is instantiated from class == class is blueprint to construct objects
* data members
- object's state or attributes
- also called fields, instance variable
* object does
- member functions
- behavior
- also called method
* class is abstract data type (struct has no operations)
* private and public
### Class
- a class is like blueprint
- a object is like the real car
- constant
* const object
- may be excuting-faster
* const data functions
* const member functions
- int function() const;
- can't used in constructor or distructor
- not allowed to modify the object (data members)
- !!!constant member function should only call constant member function
- a const member function can be overloaded with a non-const version
* if object call const member function
* if object call non-const member function
- const data member must be initialized with member initializer
- (member initializer) classA::classA():firstveriable(1),secondveriable(2)...
- static
* static data member
* class-wide 當所有物件只要一份資料時...
* global function,
* don't need to call by any object ( classname::function() or classname::attribute)
* initialized to 0 by default
- friend
- overloading
* Stream `<<` and `>>`
* global friend function
ex:
```C++
ostream &operator<<(ostream &output, const struce_name &number) {
output << "(" << number.areaCode << ")" << number.exchange << "-" << number.line;
return output; // cascaded: cout << a << b;
}
```
### Inheritance
- relationship between two classes
* composition: has-a
* Inheritance: is-a
- base(super) class <=> derived(sub) class
- tree-like hierarchy structure
- inheritate:
* Won't inheritate: constructors, destructor, and overloaded assignment operators
* friend declarations are not members, and thus not inherited
- systax:
```C++
class Child : (access-specifier->有三種) Parent {
// customized members or/and
// additional members
}
```
- access-specifier:
* public
- public => public for subclass
- private => private for subclass*
- prodect
* protected
- public => public subclass
- protected =>
* private (by default if not specified)