1. Hello, World
1
2
3
4
5
6
7
8
|
#include<iostream>
int main() {
std::cout << "Hello, World!!" << std::endl;
return 0 ;
}
|
- iostream = header file for standard input/output in C++
- std::cout = print out something in screen
- std::endl = new line
2. Namespace
식별자의 범위를 제공하는 명시적인 범위를 의미한다.
(타입의 이름, 함수, 변수 등)
예를 들어,
1
2
3
4
|
int a = 3;
int fun1(int x) {
return x;
}
|
전역 변수 a와 함수 fun1은 모두 전역 namespace에서 정의된다.
이 때, 이름이 같은 함수나 변수가 있을 때, 호출을 한다면 이름 충돌이 발생한다.
이를 방지하기 위해 namespace키워드를 사용한다.
그냥 cout>>"Hello, World">>endl; 를 입력할 땐,
using namespace std;를 제일 위에 적어주어야 하는데,
이것은 std라는 네임스페이스를 사용할 것!이라는 의미이다. (std는 standard의 약자)
쉽게 정리해서 말하자면 using namespace 선언은 말 그대로 소속을 알리는 역할이다.
그렇다면 1번의 코드에서 cout앞의 std는 namespace
- same namespace : 명시없이도 식별자가 서로에게 보인다.
- different namespace : 서로의 식별자에게 명시가 필요하다.
<namespace 생성 규칙>
- global scope에서 정의되어야한다, 또는 또다른 namespace 안에서 중첩되어야 한다
- class definition처럼 세미콜론 없이 이뤄진다
- 별칭을 사용하는 법도 있다
- namespace의 객체는 만들어질 수 없다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#include<iostream>
int a = 10;
namespace N
{
int a = 100;
void f() {
int a = 1000;
std::cout << a << std::endl;
std::cout << N::a << std::endl;
std::cout << ::a << std::endl;
}
}
int main() {
N::f();
system("pause");
}
|
::a -> global namespace
scope는 객체의 생명시간을 정해준다.
-global variable은 프로그램이 실행되는 동안은 살아있다.
- block scope 안에 있는 (중괄호) 변수들은 block of code가 실행될 동안은 살아있다.
즉, 범위 내의 코드가 실행될 동안은, 그 범위 내의 변수들은 살아있다.
3. C style support in C++
1) 선언 -> int i;
2) 포인터 -> int arr[10];
int *p = arr;
3) 포인터와 배열 -> p++; //legal
arr++; //illegal
4) call by value -> increment(x);
5) call by pointer -> increment(&x);
6) for loop -> for(int i=0; i<10; i++)
7) while loop -> while ( number < upperLimit)
8) if-else
9) switch
4. Reference
reference는 객체의 별명이라고 할 수 있다.
즉, 다시말해서 변수란 메모리 공간에 할당된 이름을 의미하는데, reference를 이용하면 같은 메모리 공간에 또 다른 이름을 부여할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
int change_val(int *p) { //pointer
*p = 3;
return 0;
}
int change_val_r(int &p) { //reference
p = 5;
}
void main() {
int num = 1;
change_val(&num); //pointer
change_val_r(num); //reference
}
|
변수를 보낼 때 그냥 보내고, 받는 callee에서 &p로 받는다
- 선언될 때, 초기화 돼야 한다
- 레퍼런스는 반드시 이미 이름을 지니고 있는 메모리 공간에 부여되어야 한다
'OOP' 카테고리의 다른 글
TermProject [1] (0) | 2019.11.12 |
---|---|
c++ [1] (0) | 2019.10.16 |