Toggle menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

미시Cpp/0316: Difference between revisions

From ZeroWiki
imported>장용운
No edit summary
imported>computer6561
No edit summary
 
(7 intermediate revisions by 3 users not shown)
Line 1: Line 1:
   ''출발합니다 안전벨트 매시구요''
   ''출발합니다 안전벨트 매시구요''
   ''식사 하고 하셨나요? 멀미가 좀 심할텐데...''  
   ''식사 하고 오셨나요? 멀미가 좀 심할텐데...''  
__TOC__  
__TOC__  
= 미시Cpp =
= 미시Cpp =
Line 90: Line 90:
* 디폴트 파라미터는 함수 프로토타입 선언을 사용할 경우 선언부에만 작성해야 한다. 정의부에서는 디폴트 값을 기술하지 않는다.
* 디폴트 파라미터는 함수 프로토타입 선언을 사용할 경우 선언부에만 작성해야 한다. 정의부에서는 디폴트 값을 기술하지 않는다.
* 디폴트 파라미터에 의해 생략이 가능한 함수를 오버로딩할 때는 모호성 에러를 피해야 한다.
* 디폴트 파라미터에 의해 생략이 가능한 함수를 오버로딩할 때는 모호성 에러를 피해야 한다.
* example
int foo(bool a, int b = 5){}


# 동적 할당 연산자 new, delete, delete[]
# 동적 할당 연산자 new, delete, delete[]
Line 111: Line 113:
# (C++11)range-based for loop
# (C++11)range-based for loop
* 범위 기반 for문을 이용하면 배열이나 STL 컨테이너를 편리하게 순회할 수 있다.
* 범위 기반 for문을 이용하면 배열이나 STL 컨테이너를 편리하게 순회할 수 있다.
* example
auto && __range = range_expression ;
for (auto __begin = begin_expr,
    __end = end_expr;
__begin != __end; ++__begin) {
range_declaration = *__begin;
    loop_statement
}


# (C++11)std::array
# (C++11)std::array
* std::array를 이용하면 편리하게 배열을 다룰 수 있다.
* std::array를 이용하면 편리하게 배열을 다룰 수 있다.
* example
#include <string>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <array>
 
int main()
{
    // construction uses aggregate initialization
    std::array<int, 3> a1{ {1, 2, 3} }; // double-braces required in C++11 (not in C++14)
    std::array<int, 3> a2 = {1, 2, 3};  // never required after =
    std::array<std::string, 2> a3 = { std::string("a"), "b" };
 
    // container operations are supported
    std::sort(a1.begin(), a1.end());
    std::reverse_copy(a2.begin(), a2.end(),
                      std::ostream_iterator<int>(std::cout, " "));
 
    std::cout << '\n';
 
    // ranged for loop is supported
    for(const auto& s: a3)
        std::cout << s << ' ';
}




== 코드 ==
== 코드 ==
* C 헤더 이용하기


{| class="wikitable"
|-
| C
| C++
|-
| #include <stdio.h>
| #include &lt;cstdio&gt;
|-
| #include <stdlib.h>
| #include &lt;cstdlib&gt;
|-
| #include <string.h>
| #include &lt;cstring&gt;
|}
기타 등등...
* namespace 키워드
using namespace std; // std 네임스페이스를 생략하고 사용가능
using std::endl; // endl만 std를 생략하고 사용가능
namespace A
{
void testMethod()
{
std::cout &lt;&lt; "A.testMethod called" &lt;&lt; std::endl;
}
}
namespace B
{
void testMethod()
{
std::cout &lt;&lt; "B.testMethod called" &lt;&lt; std::endl;
}
}
void main(void)
{
A::testMethod();
B::testMethod();
/* output
  A.testMethod called
  B.testMethod called
*/
}
* std::cout, std::cin, std::endl
#include &lt;iostream&gt; // 필요함
void main(void)
{
    std::cout &lt;&lt; "출력하는 함수" &lt;&lt; 0 &lt;&lt; 0.4 &lt;&lt; std::endl;
    // std::endl은 개행, 숫자나 실수도 출력가능
    int a;
    char * testArr[5] = {0, };
    std::cin &gt;&gt; a; // &amp; 필요없음
    std::cin &gt;&gt; testArr // 가능
}
* 참조형
void main(void)
{
    int num = 4;
    int&amp; refNum = num; // refNum은 num과 같이 취급됨, 포인터도 아니다.
    addOne(num);          // call-by-value.    num = 4로 변함
    addOne(refNum);      // call-by-reference. num = 5로 변함
}
* 함수 오버로딩
void overloadMethod();
void overloadMethod(int a);
void overloadMethod(int b, int c); // 오버로드된 함수들
* 디폴트 파라미터
void testMethod(int a, int b, int c = 5) // c는 디폴트 파라미터
void main(void)
{
    testMethod(1,2,3); // 가능
    testMethod(1,2);  // 이것도 가능
}
void testMethod(int a, int b, int c) // 정의부에는 디폴트 파라미터 금지
{
    // ....
}
* 동적 할당 연산자 new, delete, delete[]
void main(void)
{
    int * allocArray = new int[5];
    std::string * allocString = new string();
    // new로 동적할당
    delete allocString; // 메모리 해제
    delete[] allocArray; // 배열 메모리를 해제할 때 사용
}
* 클래스와 인스턴스
class TestClass // 클래스
{
};
void main(void)
{
    TestClass inst = TestClass(); // 인스턴스
    TestClass * pInst = new TestClass(); // 동적 할당 인스턴스
    delete pInst;
}
* Class 정의하기
class TestClass
{
      // 필드(멤버)나 메서드를 채워넣기
}; // 세미콜론 삽입에 주의
* 메서드 외부 정의
class TestClass
{
      void testMethod(int para1, int para2); // 프로토 타입만 정의
};
// 외부에서 testMethod 메서드를 정의함
void TestClass::testMethod(int para1, int para2)
{
      std::cout &lt;&lt; para1 &lt;&lt; para2 &lt;&lt; std::endl;
}
* '''(C++11)''' auto 키워드
auto typeArray = new int[5];
// typeArray는 자동으로 int *로 설정됨
TestClass testInst = TestClass();
auto&amp; realNum = testInst;
// realNum은 TestClass&amp;로 자동 설정됨
* '''(C++11)''' ranged-based for loop
int testArray[5] = { 1, 2, 3, 4, 5 };
for (int value : testArray)
{
// value는 순서대로 1, 2, 3, 4, 5가 대입됨
}
for (int&amp; refValue : testArray)
{
// 참조형으로도 가능
}
for ((auto 혹은 auto&amp;) value : something)
{
// 뭔가를 한다.
}
* '''(C++11)''' std::array
#include &lt;array&gt; // 필요함
void main(void)
{
    std::array&lt;type, size&gt; cppArray = { .... };
    // cppArray 아래에 있는 다양한 메서드 이용 가능
}
----


= 잡담 =
= 잡담 =
* 잘하는 애들이니깐 진도 빨리 뺄거임 브레이크 없음 - [[장용운]]
* 잘하는 애들이니깐 진도 빨리 뺄거임 브레이크 없음 - [[장용운]]
* 우주선은 관성으로 가도 되는데 튜터님이 무한 부스터를 발동하고 계신답니다... - [[유재범]]
* 우주선은 관성으로 가도 되는데 튜터님이 무한 부스터를 발동하고 계신답니다... - [[유재범]]
 
* 코드란이 비어있어서 채워갑니다! ~~틀린 것이 있을 수 있습니다.~~ - [[신형철]]
** 나이스 형철이 코드올리니까 우리있어보임ㅋㅋㅋㅋㅋ - [[장용운]]
** 감사합니다 :>! - [[신형철]]
---------------------------------------------------------------------
---------------------------------------------------------------------
[[활동지도/2015]]
[[활동지도/2015]]
[[미시Cpp]]
[[미시Cpp]]



Latest revision as of 08:23, 2 July 2015

  출발합니다 안전벨트 매시구요
  식사 하고 오셨나요? 멀미가 좀 심할텐데... 

미시Cpp

회차 : 1회차 시간 : 11시 30분 ~ 2시 30분(예정) => 12시 ~ 2시(실제) 장소 : 6층

참가원

멘토 장용운 지각
멘티 유재범 출석
신형철 출석
김성원 출석

이번에 배울 것

  • C와 C++의 차이점
  • 헤더와 include 개념 잡기
  • 네임스페이스
  • std::cout, std::cin, std::endl
  • 참조형
  • 함수 오버로딩
  • 디폴트 파라미터
  • 동적 할당 연산자 new, delete, delete[]
  • 구조체와 클래스
  • 클래스와 인스턴스
  • 클래스 정의 문법
  • 메서드 외부 정의와 헤더
  • ★(C++11)auto
  • ★(C++11)range-based for loop
  • ★(C++11)std::array

스터디 진행

내용

  1. C와 C++의 차이점
  • C++은 객체지향 프로그래밍 언어이다.
  • C는 규모적으로 C++의 subset이라고 생각하기 쉽다.
  • C++에서의 표준 라이브러리 헤더명은 .h로 끝나지 않는다.
  • 기존 C에서의 헤더를 이용하고 싶다면 <이름.h>를 <c이름>으로 선언해서 이용할 수 있다(C++호환버전).

2.헤더와 include 개념 잡기

  • 헤더는 다른 헤더의 include나 전처리기 매크로, 클래스나 함수 등의 declaration이 들어간다.
  • 외부 파일에 정의된 함수나 클래스의 declaration은 모든 파일에 필요하다. declaration이 없으면 외부에 정의된 함수나 클래스를 이용할 수 없다.
  • declaration이 있지만 definition이 없는 identifier는 링커에 의해 외부 링크가 이루어진다.
  1. 네임스페이스
  • 네임스페이스는 다른 팀원이 작성한 소스 코드와의 이름 충돌을 막아준다.
  • 네임스페이스 중괄호 블록은 같은 이름으로 다시 만들 수 있다.
  1. std::cout, std::cin, std::endl
  • std::cin, std::cout은 C++에서의 표준 입출력 스트림이다.
  • <<연산자와 >>연산자를 이용하여 모든 기본 타입을 출력할 수 있다.
  • std::endl은 줄바꿈을 의미한다.
  1. 참조형
  • 참조형은 변수의 이름을 추가 정의하는 방법이다.
  • 참조형은 선언 시 참조할 대상을 초기화해야 한다.
  • 한번 대상을 지정한 참조형은 참조 대상을 바꿀 수 없다.
  • 참조형은 포인터보다 안전한 call-by-reference 방법이다.
  • 함수 파라미터로 참조형을 이용할 수 있다.
  • 참조형을 이용하면 값의 복사가 전혀 일어나지 않는다.
  1. 함수 오버로딩
  • C++에서는 같은 이름의 함수라도 인자의 개수나 타입이 다르다면 중복 정의할 수 있다.
  • 리턴 타입만 다른 경우에는 오버로딩할 수 없다.
  • 함수를 오버로딩할 때는 실제 호출할 때 모호성이 발생하지 않아야 한다.
void func(int, int); void func(float, float);

||<-2> func(1, 2)는 왼쪽 함수가 호출된다 func(1.0, 2)나 func(1, 2.0)은 float가 int로 묵시적 형 변환이 일어나 왼쪽 함수가 호출된다 func(1.0, 2.0)은 모호성 에러가 발생한다 ||

  1. 디폴트 파라미터
  • 함수 파라미터에 디폴트 값을 지정하면 해당 인자를 생략하여 디폴트 값을 지정할 수 있다.
  • 디폴트 파라미터는 가장 우측 파라미터부터 적용해야 한다. 그렇게 강제하지 않으면 어느 인자가 생략됐는지 구분할 수 없기 때문이다.
  • 디폴트 파라미터는 함수 프로토타입 선언을 사용할 경우 선언부에만 작성해야 한다. 정의부에서는 디폴트 값을 기술하지 않는다.
  • 디폴트 파라미터에 의해 생략이 가능한 함수를 오버로딩할 때는 모호성 에러를 피해야 한다.
  • example
int foo(bool a, int b = 5){}
  1. 동적 할당 연산자 new, delete, delete[]
  • new 연산자를 이용하여 단일 변수나 배열을 편리하게 동적 할당할 수 있다.
  • 단일 변수의 해제에는 delete, 배열의 해제에는 delete[]를 이용한다.
  1. 클래스와 인스턴스
  • 클래스는 추상적 개념을 정의한 것이고 인스턴스는 그것을 구체화한 실제 변수이다.
  1. 클래스 정의 문법
  • 클래스를 정의할 땐 세미콜론을 쓴다.
  1. 메서드 외부 정의와 헤더
  • 클래스의 메서드는 클래서 정의부에 선언만 하고 외부에서 정의할 수 있다.
  • 보통 헤더에는 메서드 정의를 포함하지 않는다.

12.(C++11)auto

  • auto 키워드는 수식으로부터 타입을 추론한다.
  • auto& 키워드는 추론된 타입의 참조형을 의미한다.
  1. (C++11)range-based for loop
  • 범위 기반 for문을 이용하면 배열이나 STL 컨테이너를 편리하게 순회할 수 있다.
  • example
auto && __range = range_expression ; 
for (auto __begin = begin_expr,
    __end = end_expr; 
__begin != __end; ++__begin) { 
range_declaration = *__begin; 
    loop_statement 
} 
  1. (C++11)std::array
  • std::array를 이용하면 편리하게 배열을 다룰 수 있다.
  • example
#include <string>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <array>
 
int main()
{
    // construction uses aggregate initialization
    std::array<int, 3> a1{ {1, 2, 3} }; // double-braces required in C++11 (not in C++14)
    std::array<int, 3> a2 = {1, 2, 3};  // never required after =
    std::array<std::string, 2> a3 = { std::string("a"), "b" };
 
    // container operations are supported
    std::sort(a1.begin(), a1.end());
    std::reverse_copy(a2.begin(), a2.end(), 
                      std::ostream_iterator<int>(std::cout, " "));
 
    std::cout << '\n';
 
    // ranged for loop is supported
    for(const auto& s: a3)
        std::cout << s << ' ';
}


코드

  • C 헤더 이용하기
C C++
#include <stdio.h> #include <cstdio>
#include <stdlib.h> #include <cstdlib>
#include <string.h> #include <cstring>
기타 등등...
  • namespace 키워드
using namespace std; // std 네임스페이스를 생략하고 사용가능
using std::endl; // endl만 std를 생략하고 사용가능

namespace A
{
	void testMethod()
	{
		std::cout << "A.testMethod called" << std::endl;
	}
}

namespace B
{
	void testMethod()
	{
		std::cout << "B.testMethod called" << std::endl;
	}
}

void main(void)
{
	A::testMethod();
	B::testMethod();

	/* output
	   A.testMethod called
	   B.testMethod called
	*/
}
  • std::cout, std::cin, std::endl
#include <iostream> // 필요함

void main(void)
{
    std::cout << "출력하는 함수" << 0 << 0.4 << std::endl;
    // std::endl은 개행, 숫자나 실수도 출력가능

    int a;
    char * testArr[5] = {0, };

    std::cin >> a; // & 필요없음
    std::cin >> testArr // 가능
}
  • 참조형
void main(void)
{
    int num = 4;
    int& refNum = num; // refNum은 num과 같이 취급됨, 포인터도 아니다.

    addOne(num);          // call-by-value.     num = 4로 변함
    addOne(refNum);       // call-by-reference. num = 5로 변함
}
  • 함수 오버로딩
void overloadMethod();
void overloadMethod(int a);
void overloadMethod(int b, int c); // 오버로드된 함수들
  • 디폴트 파라미터
void testMethod(int a, int b, int c = 5) // c는 디폴트 파라미터

void main(void)
{
    testMethod(1,2,3); // 가능
    testMethod(1,2);   // 이것도 가능
}

void testMethod(int a, int b, int c) // 정의부에는 디폴트 파라미터 금지
{
    // ....
}
  • 동적 할당 연산자 new, delete, delete[]
void main(void)
{
    int * allocArray = new int[5];
    std::string * allocString = new string();
    // new로 동적할당

    delete allocString; // 메모리 해제
    delete[] allocArray; // 배열 메모리를 해제할 때 사용
}
  • 클래스와 인스턴스
class TestClass // 클래스
{
};

void main(void)
{
    TestClass inst = TestClass(); // 인스턴스
    TestClass * pInst = new TestClass(); // 동적 할당 인스턴스

    delete pInst;
}
  • Class 정의하기
class TestClass
{
     // 필드(멤버)나 메서드를 채워넣기
}; // 세미콜론 삽입에 주의
  • 메서드 외부 정의
class TestClass
{
     void testMethod(int para1, int para2); // 프로토 타입만 정의
};

// 외부에서 testMethod 메서드를 정의함
void TestClass::testMethod(int para1, int para2)
{
     std::cout << para1 << para2 << std::endl;
}
  • (C++11) auto 키워드
auto typeArray = new int[5];
// typeArray는 자동으로 int *로 설정됨

TestClass testInst = TestClass();
auto& realNum = testInst;
// realNum은 TestClass&로 자동 설정됨
  • (C++11) ranged-based for loop
int testArray[5] = { 1, 2, 3, 4, 5 };

	for (int value : testArray)
	{
		// value는 순서대로 1, 2, 3, 4, 5가 대입됨
	}

	for (int& refValue : testArray)
	{
		// 참조형으로도 가능
	}

	for ((auto 혹은 auto&) value : something)
	{
		// 뭔가를 한다.
	}
  • (C++11) std::array
#include <array> // 필요함

void main(void)
{
    std::array<type, size> cppArray = { .... };
    // cppArray 아래에 있는 다양한 메서드 이용 가능
}

잡담

  • 잘하는 애들이니깐 진도 빨리 뺄거임 브레이크 없음 - 장용운
  • 우주선은 관성으로 가도 되는데 튜터님이 무한 부스터를 발동하고 계신답니다... - 유재범
  • 코드란이 비어있어서 채워갑니다! ~~틀린 것이 있을 수 있습니다.~~ - 신형철
    • 나이스 형철이 코드올리니까 우리있어보임ㅋㅋㅋㅋㅋ - 장용운
    • 감사합니다 :>! - 신형철

활동지도/2015 미시Cpp