cpp 00

jiwoo·2022년 12월 22일
0

cpp

목록 보기
1/9

CPP 00

생성일: 2022년 11월 29일 오후 11:08
최종 편집 일시: 2022년 12월 6일 오후 9:17
태그: cpp
cpp notion

CPP Module 00

  • cpp 의 기본적인 사용법을 익힌다.
  • namespace, class, memeber fuction, stdio stream, initialization list, static, const … etc

→ notion link


개념

객체 지향

  • 실제 세계를 모델링하여 소프트웨어를 개발하는 방법으로서, 객체 지향 프로그래밍에서는 데이터와 절차를 하나의 덩어리로 묶어서 생각한다. 이는 마치 컴퓨터 부품을 하나씩 사다가 컴퓨터를 조립하는 것과 같은 방법이다.

namespace

  • 네임스페이스는 내부 식별자(형식, 함수, 변수 등의 이름)에 범위를 제공하는 선언적 영역이다. 코드를 논리 그룹으로 구성하고 코드 베이스에 여러 라이브러리가 포함된 경우 발생할 수 있는 이름 충돌을 방지하는 데 사용된다.
  • ex) include 한 여러 헤더에 같은 함수가 정의되어 있을 때, 그 함수를 사용시에 일어나는 충돌을 방지하고 어떤 헤더의 함수를 사용할 지 지정해 줄 수 있다.
  • 정규화된 이름 사용
    • std::cout (네임스페이스::요쇼)
    • AClass::Func();
  • using 선언declaration
    • using AClass::Func();
    • 하나의 식별자를 범위로 가져오기 (단 하나의 이름만을 범위 지정 연산자를 사용하지 않고도 사용할 수 있도록한다. 위의 using 선언이 있다면 AClass의 Func()를 Func();이렇게 사용할 수 있다는 뜻인 것 같다. )
  • using 지시문directive
    • using namespace std;
    • using namespace AClass;
    • 네임스페이스의 모든 식별자를 범위로 가져오기
  • std 네임스페이스
    • 모든 C++ 표준 라이브러리 형식 및 함수는 내부에 중첩된 std 네임스페이스 또는 네임스페이스에 선언됩니다. (?)
  • https://learn.microsoft.com/ko-kr/cpp/cpp/namespaces-cpp?view=msvc-170
  • http://www.tcpschool.com/cpp/cpp_scope_namespace

class

  • 함수까지 담을 수 있는 구조체라 이해할 수 있다.
  • 객체 지향 프로그래밍 (OOP, object-oriented programming
    • 모든 데이터를 객체(object) 취급하고, 객체를 중심으로 프로그래밍 한다.
    • 객체를 만들어내기 위한 개념이 class 이다.
    • 추상화, 캡슐화, 정보은닉, 상속성, 다형성의 특징을 갖는다.
  • 객체
    • 객체는 구현할 대상이다. 상태(데이터)와 기능(코드) 가 있다.
    • 클래스의 타입으로 선언 되었을 때 객체라 부른다.
  • 인스턴스
    • 선언된 해당 클래스 타입의 객체를 인스턴스라 한다. 메모리에 대입된 객체를 의미한다.
    • 객체가 메모리에 할당되어 실제 사용 될 때 인스턴스라 부른다.
  • http://www.tcpschool.com/cpp/cpp_class_intro
  • https://gmlwjd9405.github.io/2018/09/17/class-object-instance.html (객체와 인스턴스)

member function

객체를 구현하기 위한 개념 class 에 상태(데이터)와 기능(코드)를 담을 수 있는데, 멤버 함수가 이 기능(코드)를 말한다. 맞는 말인가

stdio stream

  • 스트림과 버퍼
    • 스트림
      • C++ 프로그램은 파일이나 콘솔의 입출력을 직접 다루지 않고, 스트림(stream)이라는 흐름을 통해 다룬다. 스트림(stream)이란 실제의 입력이나 출력이 표현된 데이터의 이상화된 흐름을 의미한다. 즉, 스트림은 운영체제에 의해 생성되는 가상의 연결 고리를 의미하며, 중간 매개자 역할을 한다.
    • http://www.tcpschool.com/cpp/cpp_io_streamBuffer
  • - [https://modoocode.com/143](https://modoocode.com/143)

initialization list 초기화 리스트

  • 클래스의 멤버 변수를 초기화 하는 방법 2 가지
    • 생성자 함수 블록 내에서 맴버 변수 초기화 (대입)
      • AClass::AClass(int x) { this→a = x ; }
    • 초기화 리스트로 초기화
      • AClass::AClass(int x) : a(x) {}
      • 초기화 리스트를 사용하여 const 맴버변수를 초기화 할 수 있다.
  • https://pandas-are-bears.tistory.com/16

static

  • static 멤버변수는 객체가 소멸할 때가 아닌 프로그램이 종료 될 때 소멸된다.
  • static 변수 또한 클래스 내부에서 static int num = 0; 이렇게 초기화 하는 것은 불가능하다. const static 변수일때에는 const static int num = 0; 이러한 형태로 초기화가 가능하다.
  • static 맴버함수는 객체에 종속되는 것이 아니라 클래스에 종속된다.
  • 호출시 (객체).(멤버함수) 의 형태가 아닌 (객체)::(static함수) 형식으로 호출하게 된다.
  • https://modoocode.com/197

const

  • const int AClass::function(int *x){}
  • int AClass::function(const int *x){}
  • int AClass::function(int *x) const {}
    • 해당 맴버 함수 내에서는 모든 맴버 변수를 상수화 시킨다는 의미
    • 맴버 함수 내의 지역변수는 변경할 수 있지만 클래스의 맴버 변수는 변경할 수 없다.
  • const 맴버변수는 초기화 리스트 사용
  • https://easycoding91.tistory.com/entry/C-강좌-const-위치의-의미와-사용-방법

문제

ex00 : Megaphone

받은 매개변수를 모두 대문자로 바꾸어 출력하는 문제

  • std::toupper() 는 int를 반환하기 때문에 캐스팅을 해주는 것이 좋다. c스타일에서는 (char)(명시적 형변환)로 캐스팅 해준다면 cpp스타일에서는 static_cast<char> 로 캐스팅 해줄 수 있다.
  • static_cast 는 컴파일러단에서 변환 에러를 체크 해주고 명시적변환은 런타임시 체크해준다고 하는데, 둘다 컴파일시 에러를 체크해주더라.. (테스트케이스가 잘못된걸까?) 다른 점은 포인터 형변환 시 명시적변환에서는 체크를 해주지 않는 반면 static_cast는 에러를 체크해준다.
	double	*dptr = new double(42.42);	
//	int *iptr = (int *)(dptr);
	int *iptr = static_cast<int *>(dptr);
	std::cout << "dou : " << *dptr << std::endl;
	std::cout << "(int *)" << *iptr << std::endl;

ex01 : My Awesome PhoneBook

폰북 클래스, 컨텍트 클래스 두가지 클래스를 만들고, 이를 이용하여 사용자가 ADD, SEARCH, EXIT 명령어를 입력시 적절히 동작하도록 만드는 문제

  • 클래스 생성자
    • 난나난 생성자 생성을 하지
    • 클래스이름(){}
    • 생성자는 기본적으로 "객체 생성시 자동으로 호출되는 함수”
    • 디폴트 생성자 (클래스에서 사용자가 어떠한 생성자도 명시적으로 정의하지 않았을 경우에 컴파일러가 자동으로 추가해주는 생성자)
  • 클래스 소멸자
    • 난난나 소멸자는 소멸을 시키지
    • ~(클래스의 이름)
    • 메모리누수방지
    • https://modoocode.com/188 (생성자 ㅣ 소멸자 )
  • std::cin 시
    • eof(ctrl+D) 입력 시 무한루프
      • cin.eof()
    • int 받는 곳에 문자열 입력시 fail 처리
      • cin.fail()
      • cin.clear()
      • cin.ignore(length, char)

ex02 : The Job Of Your Dreams

주어진 세가지 파일 Account.hpp, test.hpp, log 을 보고 Account.cpp를 복구하는 문제

  • class Account 안에 Account( void ); 다시 정의 ? 되어 있는 것은 무엇인가 ? 생성자인가?
  • vector 클래스
    • C++ 표준 라이브러리 벡터 클래스는 시퀀스 컨테이너에 대한 클래스 템플릿입니다. 벡터는 지정된 형식의 요소를 선형 배열에 저장하고 모든 요소에 대한 빠른 임의 액세스를 허용합니다. 임의 액세스 성능이 프리미엄인 경우 벡터는 시퀀스에 대한 기본 컨테이너입니다.
    • vector<자료형> 자료형의 배열
    • [iterator](https://learn.microsoft.com/ko-kr/cpp/standard-library/vector-class?view=msvc-170#iterator) 벡터에 있는 모든 요소를 읽거나 수정할 수 있는 임의 액세스 반복기를 제공하는 형식
  • pair 클래스
  • for_each 문
    • template <class InputIterator, class Function>
      Function for_each(InputIterator first, InputIterator last, Function fn);
    • 범위 내 (first 부터 last 전 까지) 원소들 각각에 대해 함수 fn 을 실행한다. 참고로 함수의 리턴값은 무시됩니다.
    • https://modoocode.com/260
  • time
  • amount - 계좌 금액 , deposit - 입금, withdraws 인출
    //생성자
    [19920104_091532] index:0;amount:42;created
    [19920104_091532] index:1;amount:54;created
    [19920104_091532] index:2;amount:957;created
    [19920104_091532] index:3;amount:432;created
    [19920104_091532] index:4;amount:1234;created
    [19920104_091532] index:5;amount:0;created
    [19920104_091532] index:6;amount:754;created
    [19920104_091532] index:7;amount:16576;created
    
    상태 출력
    [19920104_091532] accounts:8;total:20049;deposits:0;withdrawals:0
    [19920104_091532] index:0;amount:42;deposits:0;withdrawals:0
    [19920104_091532] index:1;amount:54;deposits:0;withdrawals:0
    [19920104_091532] index:2;amount:957;deposits:0;withdrawals:0
    [19920104_091532] index:3;amount:432;deposits:0;withdrawals:0
    [19920104_091532] index:4;amount:1234;deposits:0;withdrawals:0
    [19920104_091532] index:5;amount:0;deposits:0;withdrawals:0
    [19920104_091532] index:6;amount:754;deposits:0;withdrawals:0
    [19920104_091532] index:7;amount:16576;deposits:0;withdrawals:0
    
    추가입금
    [19920104_091532] index:0;p_amount:42;deposit:5;amount:47;nb_deposits:1
    [19920104_091532] index:1;p_amount:54;deposit:765;amount:819;nb_deposits:1
    [19920104_091532] index:2;p_amount:957;deposit:564;amount:1521;nb_deposits:1
    [19920104_091532] index:3;p_amount:432;deposit:2;amount:434;nb_deposits:1
    [19920104_091532] index:4;p_amount:1234;deposit:87;amount:1321;nb_deposits:1
    [19920104_091532] index:5;p_amount:0;deposit:23;amount:23;nb_deposits:1
    [19920104_091532] index:6;p_amount:754;deposit:9;amount:763;nb_deposits:1
    [19920104_091532] index:7;p_amount:16576;deposit:20;amount:16596;nb_deposits:1
    
    상태 출력
    [19920104_091532] accounts:8;total:21524;deposits:8;withdrawals:0
    [19920104_091532] index:0;amount:47;deposits:1;withdrawals:0
    [19920104_091532] index:1;amount:819;deposits:1;withdrawals:0
    [19920104_091532] index:2;amount:1521;deposits:1;withdrawals:0
    [19920104_091532] index:3;amount:434;deposits:1;withdrawals:0
    [19920104_091532] index:4;amount:1321;deposits:1;withdrawals:0
    [19920104_091532] index:5;amount:23;deposits:1;withdrawals:0
    [19920104_091532] index:6;amount:763;deposits:1;withdrawals:0
    [19920104_091532] index:7;amount:16596;deposits:1;withdrawals:0
    
    출금
    [19920104_091532] index:0;p_amount:47;withdrawal:refused
    [19920104_091532] index:1;p_amount:819;withdrawal:34;amount:785;nb_withdrawals:1
    [19920104_091532] index:2;p_amount:1521;withdrawal:657;amount:864;nb_withdrawals:1
    [19920104_091532] index:3;p_amount:434;withdrawal:4;amount:430;nb_withdrawals:1
    [19920104_091532] index:4;p_amount:1321;withdrawal:76;amount:1245;nb_withdrawals:1
    [19920104_091532] index:5;p_amount:23;withdrawal:refused
    [19920104_091532] index:6;p_amount:763;withdrawal:657;amount:106;nb_withdrawals:1
    [19920104_091532] index:7;p_amount:16596;withdrawal:7654;amount:8942;nb_withdrawals:1
    
    상태 출력
    [19920104_091532] accounts:8;total:12442;deposits:8;withdrawals:6
    [19920104_091532] index:0;amount:47;deposits:1;withdrawals:0
    [19920104_091532] index:1;amount:785;deposits:1;withdrawals:1
    [19920104_091532] index:2;amount:864;deposits:1;withdrawals:1
    [19920104_091532] index:3;amount:430;deposits:1;withdrawals:1
    [19920104_091532] index:4;amount:1245;deposits:1;withdrawals:1
    [19920104_091532] index:5;amount:23;deposits:1;withdrawals:0
    [19920104_091532] index:6;amount:106;deposits:1;withdrawals:1
    [19920104_091532] index:7;amount:8942;deposits:1;withdrawals:1
    
    //소멸자
    [19920104_091532] index:0;amount:47;closed
    [19920104_091532] index:1;amount:785;closed
    [19920104_091532] index:2;amount:864;closed
    [19920104_091532] index:3;amount:430;closed
    [19920104_091532] index:4;amount:1245;closed
    [19920104_091532] index:5;amount:23;closed
    [19920104_091532] index:6;amount:106;closed
    [19920104_091532] index:7;amount:8942;closed
    

0개의 댓글