수정입니다

객지프 정리 본문

전공/객체지향프로그래밍

객지프 정리

nongdamgom 2023. 12. 28. 12:52

Inheritance & Polymorphism

Inheritance

adv : reusability

disadv : occurs in run-time == slow && 상속 관계인 두 class의 coupling 증가(dependency, complexity 증가)

IS-A relationship : A is a B == A can be made a subclass of B

private : accessible only within the class definition

protected : accesiible with in the class definition or with in the definition of child classes

protected == less encapsulation

**inheritance constructor 불리는 순서

-> main에서 child 부르면 -> 부모 생성자 먼저 -> child 내에 멤버변수로 다른 class 있으면 그거 생성자 먼저 -> 그 다음 자식 생성자

=> destructor 순서는 생성자 반대로 하면 됨

class D : public B private: int y; public: D(int x_val, int y_val) : B(x_val), y(y_val){}

--> 부모 생성자 뭐 부를지 지정가능 ( 지정 안하면 default 불림)

Principle of substitution

property of OOP language

=> a variable declared as the parent type is allowed to hold a value derived from child type

--> 부모 타입으로 선언된 변수가 자식 타입의 값을 가질 수 있음

Dynamic binding

  • determining th exact implementation of a request based on both the request name and the receiving object at the run time
  • 장점 : reuseability, extensibility

--> why? dynamic binding allow us to add new classes to existing systems witout modifying the existing code

void kill(lifeform& f){ f.die(); // 바뀔 필요 x, 부모 refer type에 자식 object --> dynamic binding 일어남 // compiler does not know which implementation to execute -> run time에 결정 } int main(){ plant x; person y; kill(x); // plant die kill(y); // person die }

virtual function

  • it's behavior is defined within an inheriting class by a function with the same signature
  • that function will be redefined in the child class

--> virtual 안쓰면 static으로 binding 됨

--> static binding인데, 만약에 변수가 부모 타입이면, 실제 값이 자식 class여도 부모걸로 binding됨

  • dynamic binding 일어나는 조건
  1. the function needs to be virtual
  2. the type of the variable should be parent class pointer or reference type and actual object is child class object

--> 애초에 그냥 타입 자체가 자식 class 타입이면, binding 안일어남!! virtual이어도1!

abstract class

  • contains at least one pure virtual function

--> pure virtual function declared with "=0" means it has no implementation

--> pure virtual function is always defined in a derived class

  • no objects!!!! , can only be used as a base class
  • 목적

--> provides a uniform interface to deal with a number of different derived classes

--> delegates implementation resopnsibility to the derived class

Polymorphism

overloading == signature에 따라서 컴파일타임에 구별 됨

  • a single function name has several alternative implementations
  • typically overloaded function names are distinguished at compile time based on their type signature

overriding

  • different definitions that use the same method name with the same signature

--> run time에 결정

==> overloading == 같은 이름, 다른 파라미터

==> overriding == 같은 이름, 같은 파라미터

  • overriding

--> replacement : totally&completely replaces the code : 걍 완전 갈아 엎는거

--> refinement : 부모거 함수 부르고 + 여기에 자식이 필요한거 추가하는거

polymorphic variable

  • 변수 타입하고 object 타입 이 하나 이상인거

Template

function template

  • template <typename T>
  • typename 하나당 하나의 타입만 와야됨, 섞어 쓰려면 template <typename T, typename S> 뭐 이렇게 해야됨

class template

  • the template mechanism works for classes as well
  • this is a prticularly useful for defining container classes
  • 장점 : it store any type of element without haing to resort to "code reuse by copying"

STL(standard template libarary)

  • 3 categories of STL
  • Container clas

--> a holder object that stores a collection of other objects with any data types

--> Sequential collection : vector, list, deque

--> associative container : set, map, hash_set( O(1), but not order) -- 전부 key-value 하는 것들

--> container adapters : stack, queue, priority queue

  • Iterator

--> point to element of container

--> elements of container can be accessed through iterators

--> provide common interface to step through the elements of any arbitrary type of STL

  • Algorithm

--> perform operatons

Sequence Containers : Access, Add, Remove

* vector 에만 push_front/pop_front가 없다

vector

  • array랑 공통의 장점

--> we can directly access any data type of elemnet using index number == O(1)

--> element are stored in contiguous storage locations

  • array랑 비교해서 vector 장점

--> it can be resize itself automatically when inseting or erasing a vector element

  • array랑 비교해서 vector 단점

--> vector memory management is dynamically, so performance is slower than array

  • 중간에 삽입/삭제

--> O(n) -- move all the other element all position backword, 효율적 x

--> 이런건 linked list가 빠르다(O(1))

  • member function

--> size() vs capacity()

--> size는 현재 들어있는 원소 개수(지금 얼마 들어있는지), capacity는 현재 할당된 storage 크기(얼마나 넣을 수 있는지)

** max_size() : maximal possible capacity

iterator

  • vector<type>::iterator variable name;
  • *variable name == the value at this iterator

container
access/retrieval
insert/erase
vector(1D)
O(1) random access
O(1) at back only
O(n) at front, in middle
list(doubly-liked)
O(a) at front/back only
No random access(O(n))
O(1) at any position
deque(doubly-ended)
O(1) random access
O(1) at front/back only
O(n) in middle

vector 장점 케이스

float temp; while (cin >> temp){ a.push_back(temp); }

--> array로 다루기 힘들다(input 몇개 올지 몰라서)

const 쓰는 이유

  • improve readability & safety
  • why? : it guarantee that argument value doesn't change

7-2 STL Iterators

A pair of iterators can be used to indicate a subsequence

  • (Iterator 1, Iterator2) ==> value Iterator 1 ~ Iterator2 -1
  • access element : *p, p->
  • begin(), end()

Why are Iterators So Great?

=> without iterator, we have to implement operation of each container

=> can access elements of sequence container without differentiating between different container classes

ex) Find()

=> FInd() function contains no information about the implementation of the container or how to move th eiterator from one element to the next

=> Find() can be used for any container that provides a suitable iterator

7-3 STL Algorithms

  • sort(), find(), find_if()... etc

--> 여기서 쓰는 sort() --> user-defined type 넘겨줄거면, 정렬 할 기준이 있어야함

--> 변형 quick sort == worst&avg 둘다 O(nlogn)

--> vector, deque에는 있는데 list에는 x

* sort() + user defined 사용법

  1. 3번째 파라미터로 그 클래스에서 정의한 static member function or 그냥 밖에 있는 아무 function 넘겨주기
  2. 3번째 파라미터 안쓰고, 그냥 operator overloading으로 해결
  3. 새로운 class 생성 후 그 object를 function처럼 사용 (functor) -> const 필요..
  4. lambda funtion으로 바로 기준 작성

find() 쓸 때는, bool operator == overloading 해줘야 함

find_if() -> 3번 째 파라미터에 condition주는 함수 넣기

transform(인풋 시작점, 인풋 끝점, 아웃풋 시작점, 함수)

--> input 자료에, 함수를 해서, 아웃풋 자료를 만듬

transform(a 인풋 시작점, a 인풋 끝점, b 인풋 시작점, a 아웃풋 시작점, 함수)

--> a 에 b를 함수 하는 것

Miscellaneous

  • Functor
  • myfunct(10) == myfunct.operator()(10);
  • 장점 : more flexible

auto

  • 초기화 무조건
  • vector<int>::iterator it = vec.begin(); 이거를
  • auto it = vec.begin() 이렇게 가능
  • type of variable is automatically deduced

decltype

  • extract type form variable
int a = 5; decltype(a) b = a+7; ==> int b

range-based for loop

for(int x: vec) for(auto x: vec) for(auto& x: vec)

UML(Unified Modeling Language)

System : a set of interacting or interdependent entities forming an integrated whole

Modeling : describing a software system at a high level of abstraction

Unified : UML has become a world standard

What is UML?

  • industry-standard
  • graphical notations
  • Simplifies
  • not dependent on any one language or technology
  • 3 categories
  1. Sturcture Diagrams - class
  2. Behavior Diagrams - use case, activity
  3. Interaction Diagram - sequence

class diagram : static structure

use-case : represented as use cases and any dependencies between those use cases

activity : step-by-step workflows, shows overall flow of control

==> diagram ::: multiple aspects