c++

C++ Primer CH1. Getting Started

big whale 2024. 1. 21. 15:53

 

c++ 필독서라는 c++ primer를 읽고 노션에 정리한 글이다.

 

ch1 - getting started 

OS는 main() 함수를 호출함으로써 프로그램 시작시킴.

main() 인자에는 값을 넣을 수도 있음

 

main()은 int 반환함, int: built-in type(언어가 정의하는 타입)

; → statement가 끝났다는걸 표시하기 위함.

main()이 0 리턴 → 정상 종료

main()이 다른 값x 리턴 → x에 해당하는 error 발생

 

stream이란? read되거나 written되는 sequence of char through io device

왜 stream이란 이름이 붙였나? → generated, consumed, sequentially over time 느낌을 주기 위해

 

iostream == istream + ostream

istream = cin, ostream = cout

cerr, clog

 

#include directives(지시자)

cout << endl 의 역할

  • 현재 라인 끝났다는 표시 + 줄바꿈
  • output buffer flush 해줌.
    • flush 효과: 쓰기로 되어 있었던 모든 데이터들이 실제로 stream에 써졌다.(generated outputs are all written to output stream rather than sitting in memory waiting to be written)
    • printf() 찍어서 디버깅할 때 flush 계속 해줘야 함.
      • 이유: 프로그램 crashed시 buffer에 output 남아있어서 difficult to find where the program crashed

std::cout, std::endl에서 std는 namespace 타입이다.

모든 standard library 메서드는 std 네임스페이스 안에 있다.

 

int a = 0 → a 변수 생성하자마자 0이라고 초기화(initialized) 해주는 것.

cin(istream), cout(ostream)은 >>, << 결과 각자의 object를 반환하는데, operand가 invalid할 경우 error가 발생하고 이 error가 condition에 위치하면 false가 된다. → while (cin >> val) 이렇게 하면 valid input일 경우에만 돌게 만들 수 있다. 아니면 EOF(파일끝)면 된다.

 

그리고 EOF(end of file)은 키보드로 입력할수도 있다. os마다 입력방식이 다른데, windows에서는 ctrl+z, unix에서는 ctrl+d다.

 

syntax error, not defined(declaration) error, type error

 

<>: standard library

“”: not standard library

 

Sales.item.h 코드 읽기

friend 라는 identifier가 있다. → private에 접근할 수 있도록 해줌.

각 클래스가 operand가 될 때, operator별로 어떤 로직이 수행될지 코드로 작성할 수 있다.

inline bool operator==(const Sales_item &lhs, const Sales_item &rhs)
Sales_item operator+(const Sales_item&, const Sales_item&);
Sales_item& Sales_item::operator+=(const Sales_item& rhs);

item1.operator+=(item2)

 

어떤 함수가 const(상수 멤버함수) 값 리턴 → 이 함수는 내부 상태를 변경하지 않음을 보장.

  • 만약 내부상태 변경코드가 있으면, 컴파일시 컴파일러가 이를 캐치한다.

&는 변수앞에 붙으면 해당 변수의 주소를 반환하고, 함수 인자에 붙이면 해당 변수의 주솟값을 받겠다라는 것이됨.

cin은 operand가 완성될 때 istream(cin)객체 생성된다.