2016년 3월 12일 토요일

C++ 공부 - 입출력, 오버로딩, 이름공간,

 chap1. C언어 기반의 C++
 
1.입출력방식
 
#include <iostream>
 
- 표준 헤더파일 선언시 확장자 생략
 
std::cout<<“이름”<<name<<lang<<std::endl;
 
- <<를 이용한 연이은 출력가능. 자료형 무관.
- std::end1<<를 이용해 출력하면 개행.
 
std::cin>>val1>>val2>>lang;
 
- >>를 이용한 연이은 입력가능. 자료형 무관.
- 입력받는 데이터간 경계는 공백에 의해 나누어짐.
 

CF) C언어 복습 포인터, 배열
 
1. 일차원 포인터
 
int* pointer = NULL;
char a = ‘A’;
char* pointer2 = &A;

- “char형의 주소를 보관하겠다는 의미
- *는 값을 참조, &는 주소 값을 의미하며 서로 상쇄됨.
 
sizeof(int*) sizeof(int**)

- 포인터 변수는 모두 4바이트
 
2. 배열
 
int array[3] = {1,2,3};
 
- 1차원 배열의 이름은 배열의 시작주소
- *(array+i) == array[i] == *&array[i]
 
int array[2][2] = {{10,20},{30,40}};
 
- 2차원 배열의 이름은 2차원 배열의 시작주소
- 2차원 배열에서 array[i]는 행을 대표하는 주소

array == array[0] == &array[0][0]
array[i] == &array[i][0] == *(array+i)
 
 
3. 다차원 포인터

int num = 30;
int* p1 = &num;
int** p2 = &p1;
 int*** p3 = &p2; //-1차원 포인터의 주소를 저장하겠다.
 
2. 함수 오버로딩
 
같은 이름을 가진 함수 선언 가능(argument의 종류, 수로 구분)
 
3. 매개변수의 디폴트값
 
int add(int a = 7, int b = 5);
add(); add(5); add(3,6);
 
- 선언된 변수의 수보다 적은 수의 인자전달 가능!
- 전달되는 인자는 왼쪽부터 채워지며, 부족분은 디폴트 값으로 사용됨.
 
int add(int a, int b=5); //가능
int add(int a=3, int b); //불가
 
- 왼쪽부터 인자가 전달되므로, 디폴트 값은 오른쪽부터 채워야함.
 
4. 인라인 함수
 
매크로함수의 장점유지(빠르다), 단점 보완(구현 어렵다).
인라인 함수의 몸체부분이 함수 호출 문장을 완전히 대체하는 것.
매크로함수는 전처리기에 의해, 인라인함수는 컴파일러에 의해 처리.
 
5. 이름공간
 
이름공간을 만들고, 그 안에 선언하면 같은 이름의 함수, 변수 사용 가능.
 
namespace C1{
 
      namespace C2{
            int Adder(int a,int b);
            void Pretty(void);
      }

      int C1::adder(int a,int b){
            pretty();
            return a+b;
      }

      void C1::Pretty(){
            std::cout<<“pretty”;
      }
 
      int Adder(int a,int b);
      void Pretty(void);
      }
 
      int C2::adder(int a,int b){
            pretty();
            C1::pretty();
            return a+b;
      }
       void C2::Pretty(){
            std::cout<<“pretty”;
      }
 
- 이름공간에는 선언만, 아래에 :: 이용하여 정의 가능.
- :: 범위지정연산자(scope resolution operator), 이름공간 지정시 사용.
- 같은 이름공간에 정의된 함수 호출시에는 이름공간 명시 x.
- 이름공간의 중첩역시 가능, 이 경우 ::를 반복 사용하여 접근
 
 
문제 1-4[파일의 분할]
 
#include
This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the -I option (see Invocation).
시스템 헤더를 include하는데 사용합니다.
 
#include "file"
This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for . You can prepend directories to the list of quote directories with the -iquote option.
유저의 헤더를 include하는데 사용합니다.
 
6. using을 사용한 이름공간의 명시.
 
using std::cin;
using std::endl;
 
- “cin, endl은 이름공간 std에서 찾으라의 의미.
- 이후 std:: 없이 사용가능.
- 함수 내에서 선언 시, 함수 밖에서 효력 x, 전역 선언 가능.
 
using namespace std;
 
- 이름공간 std의 모든 것에 접근할 때, 이름공간 지정을 생략한다의미
- 좋은 습관 아님. 윗 방식대로 사용할 것.
 
+지역변수와 전역변수의 이름이 같으면, 전역변수는 지역변수에 의해 가려짐. 이때 ::를 변수 이름 앞에 붙이면 전역변수를 의미함.

댓글 없음:

댓글 쓰기