노력과 삽질 퇴적물

CPP: C++가 보이는 그림책 01~07장 본문

프로그래밍note/언어. C&C++ 계열

CPP: C++가 보이는 그림책 01~07장

MTG 2012. 3. 5. 17:04


컴파일러를 쓸수 있는 환경이 아니라도, 코드패드(http://codepad.org/)에서도 테스트 해볼수 있는 기본적인 예제코드입니다.






01장.


1. cout과 endl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream> // *.c에서는 #include <stdio.h>인 방식.
 
using namespace std;
 
int main()
{
    float r = 3.14;
    char author[] = "MTG";
 
 
    //C출력    출력연산자(<<)    "문자열"    출력연산자(<<)    endl;
    cout << "출력문_경우_01" << endl//ENDL = END LINE = /n
    cout << "출력문_경우_02\n\n";
 
    cout << 'A' << endl;
    cout << 100 - 10 << endl;
    cout << 3.14 << endl;
 
    cout << 123 << endl
            << 456 <<endl
            << 789 <<endl;
 
    cout << "\t" << 2011 << "년 " << 07 << "월 " << 05 << "일\n";
    cout << "\t작성자: " << author << endl;
 
 
 
    return 0;
}
/* C++프로그램 구조
    1. main함수의 첫번째 문장부터
    2. main함수내 두번째 문장이 차례대로 실행.
    3. 종료: main내 마지막문장에 도달
        || return문
        || exit함수의 실행.
*/
cs



2. ASCII변환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
using namespace std;
 
int main()
{
    int ascii_key; // = 65;
    char limit = 'Z';
 
    for (ascii_key = 65; ascii_key <= (int)limit; ascii_key++)
    {
        cout << "ASCII_val " << ascii_key << " = " << (char)ascii_key << endl;
    }
    cout << "\n" << endl;
 
    return 0;
}
cs



 3. 출력문, 문자열

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string> // strcpy()함수와 string자료형 사용을 위해.
#include <conio.h>
 
using namespace std;
 
int main (int argc, char *argv[])
{
    char str1[] = "문자열_char str1[]";
    string str2 = "문자열_string str2";
    string str3 = "+첨가물";
 
    cout << "char str1[] = " << str1 << endl;
    cout << "string str2 = " << str2 << endl;
    cout << "string str3 = " << str3 << endl;
    cout << "\n\n";
 
    strcpy(str1, "overwrite");
    cout << "strcpy(str1, ""overwrite"")      == " << str1 << endl;
    strcpy_s(str1, str3.c_str());
    cout << "strcpy_s(str1, str3.c_str()) == " << str1 << endl;
    str2.append(str3);
    cout << "str2.append(str3)            == " << str2 << endl;
    str2.swap(str3);
    cout << "str2.swap(str3)                 == " << str2 << endl;
    getch();
 
    return 0;
}
cs



 4. 출력문, 자릿수 제어

setw(X)를 이용해서 들여쓰기*우측정렬형태가 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
 
int main ()
{
    float num = 1.23456789;
 
    cout << "setw(5)                 == "
        << setw(5<< 100 << endl;//[*.c] %5d
    cout << "setw(5) << setfill('0') == "
        <<  setw(5<< setfill('0'<< 100 << endl;
    cout << num << endl;
    cout << "setw(6)                    == "
        << setw(6<< num << endl;
    cout << "setw(6) << setprecision(3) == "
        << setw(6<< setprecision(3<< num << endl;//[*.c] %0.3f
    getch();
 
    return 0;
}
cs



 5. 간단한 입출력(cin, cout)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <conio.h>
 
using namespace std;
 
int main()
{
    int in_num = NULL;
 
    cout << "cin >> in_num;" << endl;
    cout << "정수입력: ";
    cin >> in_num;
    cout << in_num << endl;
    cout << "press to any key ";
    getch();
 
    return 0;
}
cs






02장.

 1. 연산자
① 증감 연산자
int a = 0;
a++; // -> a = a + 1
int b = 0;
b--; // -> b = b - 1

② 축약 연산자
a += b; // -> a = a + b;
a -= b; // -> a = a - b;
a *= b; // -> a = a * b;
a /= b; // -> a = a / b;
a %= b; // -> a = a % b;

③ 논리 연산자
&& AND
|| OR
! NOT // ---> a != 100, [a ≠ 100]a는 100이 아니다.

④ 조건 연산자
(expression) ? (val_01) : (val_02)
//조건식 ? true : false
//조건식을 검사해서, 참이면 val_01. 거짓이면 val_02






03장.

 1. 외부함수 사용법 4가지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <conio.h>
 
using namespace std;
 
int    func_1(int in_a, int in_b); // 인수O, 반환값O
void func_2(float in_c); // 인수O, 반환값X
int    func_3(); // 인수X, 반환값O
void func_4(); // 인수X, 반환값X
 
 
 
int main()
{
    int a = 0;
    int b = 0;
    int result_func1 = 0;
    float c = 0;
    int result_func3 = 0;
 
 
    cout << "함수사용법4가지\n\n" << endl;
 
    cout << "int func_1(int in_a, int in_b);// 인수O, 반환값O" << endl;
    cout << "\t정수 a 입력: " ;
    cin >> a;
    cout << "\t정수 b 입력: " ;
    cin >> b;
    result_func1 = func_1(a, b);
    cout << "\tfunc_1(" << a << "," << b << ") == result_func1 == " 
            << result_func1 << "\n" << endl;
 
    cout << "void func_2(float in_c);// 인수O, 반환값X" << endl;
    cout << "\t정수 c 입력: " ;
    cin >> c;
    func_2(c);
 
    cout << "int func_3();// 인수X, 반환값O" << endl;
    result_func3 = func_3();
    cout << "\tfunc_3() == n *= n == " << result_func3 << "\n" << endl;
 
    cout << "void func_4();// 인수X, 반환값X" << endl;
    func_4();
    getch();
 
    return 0;
}
 
 
 
int    func_1(int in_a, int in_b) // 인수O, 반환값O
{
    int sum = in_a + in_b;
 
    return sum;
}
 
void func_2(float in_c) // 인수O, 반환값X
{
    float tmp = in_c;
    cout << "\tfunc_2(" << tmp << ") == result_func2 == " << ++in_c << "\n" << endl;
 
    //return ;//생략가능
}
 
int    func_3() // 인수X, 반환값O
{
    int n = 10;
    n *= n;
 
    return n;
}
 
void func_4() // 인수X, 반환값X
{
    cout << "\tvoid func_4()" << endl;
    cout << "\t인수X, 반환값X" << endl;
    cout << "\t작성자: MTG" << endl;
}
cs


 2. 전역변수&지역변수

#include <iostream>
#include <conio.h>

using namespace std;

int val = 13;

int main()
{
	int val = 5;

	cout << "지역변수   val == " << val << endl;
	cout << "전역변수 ::val == " << ::val << endl;
	cout << "\n";
	getch();

	return 0;
}


 3. 다형성, 오버로드

#include <iostream>
#include <conio.h>

using namespace std;

void function();
int    function(int number);
float function(float number);



int main()
{
	float in = 0;
	int type_size = 0;
	int result_i = 0;
	float result_f = 0;

	cout << "정수나 실수를 입력하시오: ";
	cin >> in;
	type_size = sizeof(in);

	if ( in != (int) in ) //float인지 체크
	{
		result_f = function(in);
		cout << "\t(float) 2 * " << in << " == " << result_f << endl;
	}
	else if ( in == (int) in) //int인지 체크
	{
		result_i = function(in);
		cout << "\t(int) 2 * " << in << " == " << result_i << endl;
	}
	else
	{
		function();
	}
	getch();



	return 0;
}


 4. 다형성, 함수템플릿(*.cpp 한정)

#include <iostream>
#include <conio.h>

using namespace std;
template <typename datatype>
//template <class class_t>//클래스에도 사용가능?

datatype sum(datatype a, datatype b)
{
	return (a + b);
} // 자료형과 표현하는 방식이 달라도 기본적인 처리법이 같을때 유용.



int main()
{
	int    a_i, b_i, c_i;
	float a_f, b_f, c_f;

	cout << "정수1 입력: ";
	cin >> a_i ;
	cout << "정수2 입력: ";
	cin >>  b_i;
	cout << "실수1 입력: ";
	cin >> a_f;
	cout << "실수2 입력: ";
	cin >>  b_f;

	c_i = sum(a_i, b_i);
	c_f = sum(a_f, b_f);

	cout << "\t정수 : " << c_i << endl;
	cout << "\t실수 : " << c_f << endl;
	getch();



	return 0;
}


 5. 파일분할법


주의!

-> extern int g_var1; //main소스등에 있는 변수를 참조해온다.(소스파일 외부변수 참조)

-> static  int g_var2; //선언된 파일내에서만 참조가능.

-> const  int g_var3; //해당변수에는 새로운값으로 재정의 불가.

// m_header.h



void func_1(...);

...

void func_k(...);











// m_function.cpp


#include "m_header.h"


void func_1(...)

{   ...   }

...

void func_k(...)

{   ...   }

// main.cpp


#inlcude <iostream>

#include "m_header.h"

//#include "m_function.cpp" 필요X


int main()

{

     func_1(...);

     ...

     func_k(...);


return 0;

}

↓↓(프로그램상 아래처럼 인식)

#inlcude <iostream>

#include "m_header.h"



int main()

{

     func_1(...);

     ...

     func_k(...);



     return 0;

}



...(m_function.cpp에 있는 함수정의가 자동으로 배속되는 격?)...






04장.

 1.함수인자,  일반&포인터 변수


이중포인터.
int a = 10;
int *ptr = &a;
int **d_ptr = &ptr;

   ptr == a의 주소값   /   d_ptr == ptr의 주소값
 *ptr == a의 내용물   /   *d_ptr == ptr 내용물
**d_ptr == ptr에 저장된 주소값의 내용물[*ptr]

          == a의 내용물

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
 
void trade_1(float *a, float *b);
void trade_2(float &a, float &b);
 
int main()
{
    int set_n = 10;
    float f_a = 1234;
    float f_b = 5678;
    float f_print = 0;
    float *p1 = &f_a; //간접연산자(*)로 포인터 선언
    float *p2 = &f_b; //간접연산자(*)로 포인터 선언
 
 
    cout << "「------------------------------------------------------" << endl;
    cout << " |  *p변수명      = &일반변수명;                           |" << endl;
    cout << " |  &일반변수명 =   일반변수명;                            |" << endl;
    cout << " |  [일반변수]     변수명 => 내용물,   &변수명 => 주소값    |" << endl;
    cout << " |  [포인터변수] p변수명 => 주소값,  *p변수명 => 내용물     |" << endl;
    cout << " _________________________________________________________」" << endl;
    cout << "\n" << endl;
 
    cout << "float *p1 = &f_a; \t float *p2 = &f_b;" << endl;
    cout << "     "
            << setw(set_n) << "f_a == " << f_a << setw(set_n) << ", *p1 == " << *p1
            << setw(set_n) << ", &f_a == " << &f_a << endl;
    cout << "     "
            << setw(set_n) << "f_b == " << f_b << setw(set_n) << ", *p2 == " << *p2
            << setw(set_n) << ", &f_b == " << &f_b << endl;
    cout << "\n" << endl;
 
    trade_1(&f_a, &f_b); // *a = &f_a, *b = &f_b
    cout << "trade_1(&f_a, &f_b); // *a = &f_a, *b = &f_b" << endl;
    cout << "     "
            << setw(set_n) << "f_a == " << f_a << setw(set_n) << ", *p1 == " << *p1
            << setw(set_n) << ", &f_a == " << &f_a << endl;
    cout << "     "
            << setw(set_n) << "f_b == " << f_b << setw(set_n) << ", *p2 == " << *p2
            << setw(set_n) << ", &f_b == " << &f_b << endl;
    cout << "\n" << endl;
 
    trade_2(f_a, f_b); // &a = f_a, &b = f_b
    cout << "trade_2(f_a, f_b); // &a = f_a, &b = f_b" << endl;
    cout << "     "
            << setw(set_n) << "f_a == " << f_a << setw(set_n) << ", *p1 == " << *p1
            << setw(set_n) << ", &f_a == " << &f_a << endl;
    cout << "     "
            << setw(set_n) << "f_b == " << f_b << setw(set_n) << ", *p2 == " << *p2
            << setw(set_n) << ", &f_b == " << &f_b << endl;
 
    getch();
 
    return 0;
}
 
 
 
void trade_1(float *a, float *b) // float *a = &f_a, float *b = &f_b
{
    float tmp = 0;
    tmp = *a;
    *= *b;
    *= tmp;
// 포인터 인수로 참조전달
void trade_2(float &a, float &b) // float &a = f_a, float &b = f_b
// 참조형 &a와 &b
    float tmp = 0;
    tmp = a;
    a = b;
    b = tmp;
}
 
cs


 2. 포인터 변수, 주소갑과 참조값


주소값 표현

참조값 표현

&arr[a][b]

arr[a] + b

*arr + n

*(arr[a] + b)

*(*arr + n)

*(*(arr +a) + b)

(*(arr + a))[b]


이중포인터.
int a = 10;
int *pointer = &a;
int **d_pointer = &pointer;

   pointer == a의 주소값
d_pointer == pointer의 주소값

 *pointer     == a의 내용물
**d_pointer == pointer에 저장된 주소값의 내용물
                 == a의 내용물

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	int set_n = 21;
	int arr[2][2] = {{20, 11}, {7, 10}};
	int i;
	int j;
	int n;


	for (i= 0, n =0; i<2; i++)
	{
		for (j= 0; j<2; j++, n++)
		{
			cout << " arr[" << i+1 << "]" << "[" << j+1 << "] == 내용물 " << arr[i][j] << endl;

			cout << "주소값"  << setw(set_n) << "&arr[i][j] == "
 
<< &arr[i][j] << endl; cout << "주소값" << setw(set_n) << "arr[i] + j == "
 
<< arr[i] + j << endl;
cout << "주소값" << setw(set_n) << "*arr + n == "
 
<< *arr + n << endl; cout << "참조값" << setw(set_n) << "*(arr[i] + j) == " << *(arr[i] + j) << endl; cout << "참조값" << setw(set_n) << "*(*arr + n) == " << *(*arr + n) << endl; cout << "참조값" << setw(set_n) << "*(*(arr + i) + j) == "
 
<< *(*(arr + i) + j) << endl; cout << "참조값" << setw(set_n) << "(*(arr + i))[j] == "
 
<< (*(arr + i))[j] << endl; cout << "\n"; } } return 0; }
Joinc: 다양한 포인터 활용 예제들


 3. 문자열, 변환과 복사
strcpy(char_A, char_B);
char str1[];
char str2[] = "문자배열로도도 덮어지기 가능.";
strcpy(str1, "새로 덮어씌워지는 문자열");
strcpy(str1, str2);

strcat(char_A, char_B);
char str3[] = "가나다라";
char str4[] = "마바사아";
strcat(str3, str4); // -> str3을 출력시, 가나다라마바사아

//문자열을 숫자로 변환
int atoi (const char *nprt);
-> int n1 = atoi("1234"); //n1 = 1234;

long atol (const char *nprt);
-> long n2 = atil("-1234567");

float atof (const char *nprt);
-> float n3 = atof("1.234");


 4. 변수, 정적변수와 동적변수
정적(static) 변수
-> 지역변수에 사용시, 글로벌변수같은 '기억수명'(혹은 범위)를 가진다.
예. static int loc_var = 0;


동적 변수
-> 프로그램 시작시, 비활성이나 필요할때 메모리를 점유하고 사용후 폐기되어 메모리관리가 용이.
예1. int *pNum = new int; //동적변수로 확보
delete pNum;//동적변수 삭제

예2. int num = 10;
int *pNum = new int[num]; //배열크기만큼의 동적배열 확보.
delete [] pNum;//동적변수 삭제

클래스의 경우 아래처럼(?)
class SampleClass
{
    public:
        ... ... ...
};


... ... ...
int main()
{

    SampleClass *sample[2];

    sample[0] = new Sample;

    sample[1] = new Sample;

...

}





05장.

 1. 구조체, 연합체와 열거형

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
 
using namespace std;
 
struct list_1
{
    int num;
    char name[10];
}; // 클래스와 달리 함수를 멤버로 포섭불가.
list_1  p1;
list_1  p2;
list_1 *pt_s = &p2;
 
union list_2
{
    int num;
    char name[10];
};
list_2 p3;
list_2 p4;
 
//열거형은 멤버들의 변호가 0부터 시작.
enum list_3 {sunday, monday, tuesday, wednesday, thursday, friday, satday};
list_3 p5;
 
 
int main()
{
    int select_n = 0;
 
 
    //    people p1 = {5, "홍길동"};
    p1.num = 5;
    strcpy(p1.name, "홍길동");
    pt_s->num = 8// (*pt_s).num;
    strcpy(pt_s->name, "장길산");
 
    //구조체
    cout << "구조체" << endl;
    cout << p1.num << p1.name << endl;
    cout << pt_s->num << pt_s->name <<endl;
    cout << "\n" << endl;
    p3.num = 30;
    strcpy(p3.name, "아무개");
    p4.num = 25;
    strcpy(p4.name, "반딧불");
 
    //연합체
    cout << "연합체" << endl;
    cout << p3.num << p3.name << endl;
    cout << p4.num << p4.name << endl;
    cout << "\n" << endl;
    // 구조체처럼 배정된 메모리를 분배하는게 아니라 독단적으로 사용하는 경향?.
    // 멤버들을 한꺼번에 사용하는데 부적절.
 
    //열거형
    cout << "열거형" << endl;
    cout<< "0~6중 1가지 숫자를 입력하세요: ";   
    cin >> select_n;
    p5 = (list_3)select_n; //입력된 값을 열거형으로 캐스트
    if (p5 == sunday)
    {
        cout << "오늘은 일요일[" << p5 << "]" << endl;
    }
    cout << "\n" << endl;
 
    return 0;
}
cs





06장.

 1. 클래스


* 클래와 구조체의 차이점

> 언어적 차이: 구조체 멤버는 기본이 public이고, 클래스 멤버는 기본이 private

struct 와 class 의 차이점. - GpgStudy 포럼

class myClass
{
     public: //클래스 외부공개
      ... ;

     protected: //클래스 외부 비공개. 단, 파생클래스(상속받은)만 전급가능.
      ... ;

     private: //클래스 외부 비공개. 은폐
      ... ;


     public:
     myClass(...); //생성자
     ~myClass(); //소멸자
};
//개체선언
myClass object_1;
myClass object_2;
...;


void myClass::myFunction() // 클래스정의시 선언한 함수.
{
     ...;
}
void myClass::myClass() // 생성자정의.
{
     /*
     -> 클래스 개체 생성시, 자동으로 호출되는 특수 함수.
     -> 클래스 개체 선언시, 초기화를 잊어버리는것을 방지.
     -> 자신이 속한 클래스와 동명.
     -> 반환값X, 인수(있거나 없거나), 다중정의O
     */ 
}
void myClass::~myClass() // 소멸자정의.
{
      /*
      -> '~'라는 연산자가 붙는다.
      -> public영역에서만 선언해야한다.
      -> 반환값X, 인수X, 다중정의X 
      */ 
}


int main()
{
     myClass object; //클래스형으로 선언된 변수 => 개체 or 인스턴스생성 == 생성자 함수 호출
     ...;
}



 2. 네임스페이스
-> 중복 및 범위유효성때문에 길고 복잡하게 명명하게 된다. 타이핑을 하다보면 불편해지기 때문에

     namespace IamFullNameNameSpace   { ... ... }

     namespace shortenName = IamFullNameNameSpace; 로도 사용 가능하다.

① using 지시자(Directive)

namespace CustNS
{
    int data1;
    double data2;
    void excute()    {    printf("hello");    }
}

using namespace CustNS;


void main()
{
     data1 = 2014;
     data2 = 7.15;
     excute();

}








ⓢ 소속지정(?)

namespace CustNS
{
    int data1;
    double data2;
    void excute()    {    printf("hello");    }
}

void main()
{
    using namespace CustNS;
    data1 = 2014;
    data2 = 7.15;
    excute();
}

void f1()

{
     CUST_NS::data1 = 1024;
     CUST_NS::data2 = 3.14;

     CUST_NS::excute();
}

③ using 선언(Declaration)

namespace CustNS
{
    int data1;
    double data2;
    void excute()    {    printf("hello");    }
}

void main()
{
    using namespace CustNS:data2:
    UST_NS::data1 = 2014;
    data2 = 7.15
    UST_NS::excute();
}







혼자 연구하는 C/C++ by WinAPI (SoEn, 구: WinAPI)

-> 네임 스페이스 작성 규칙

-> 네임 스페이스 사용

-> using 선언


Yang-gaeng's Blog :: 네임스페이스(namespace) 란?






07장.

 1. 가상함수, virtual
#include <iostream>

using namespace std;

class Base
{
public:
void func_1(...);
virtual void func_2(...);
virtual void func_3(...) = 0; //순수가상 함수. 함수 본체가 없다는 뜻
//'순수가상함수'가 1개라도 있으면 개체생성불가??
}; //추상클래스이다.

가상함수: 상속된 클래스에서 재정의 선택사항.

순수가상함수(Pure Virtual Function): 상속된 클래스에서 재정의 필수사항.






기타.


人生不學이면, 如冥冥夜行이니라.... :: 기초를 쌓자(1) - C,C++/const 편

[Effective C++] - const 정리 : 네이버 블로그






자료.

참고서적.

C++가 보이는 그림책
ANK Co.Ltd 저
김성훈 역
성안당

ISBN:9788931548761

웹 레퍼런스
Reference - C++ Reference

블로그.
visual studio 2010 도스창 그냥 꺼지는 오류






기타. 변경이력


일자

변경이력

2013-03-05

 초안

2014-10-30

 04장. 4. 변수, 정적변수와 동적변수, 클래스의 경우 추가.