본 문서는 인프런의 [하루 10분|C++] 누구나 쉽게 배우는 C++ 프로그래밍 입문 강의를 공부하며 작성한 개인 노트입니다.
C++는 복합데이터형을 제공한다.
배열: 같은 데이터형의 집합
typeName arrayName[arraySize];
short month[12] = {1, 2, 3};
month[3]
를 출력하면 결과는 0특징
char a[6] = { 'H', 'e', 'l', 'l', 'o', '\0' };
strlen
- 배열의 길이 반환
#include <cstring>
(예) strlen(name1)
cin
- 입력 받아서 변수에 저장
cin >> name1; //name1은 변수
cin.getline(변수, 최대크기);
- 줄 단위로 입력 받음
getline
과 기능 유사cpp.getline(name1, Size);
-cin
으로 string 객체에 입력 저장 가능
cout
으로 string 객체를 디스플레이string str1 = "jinny";
cout << str1[0] << endl; // "j" 출력
구조체: 다른 데이터형이 허용되는 데이터의 집합
struct MyStruct
{
string name;
string position;
int height;
int weight;
};
MyStruct A = {
"Jinny",
"Student",
185,
80
};
cout << A.name << endl;
MyStruct A[2] = {
{"A", "A", 1, 1},
{"B", "B", 2, 2}
};
cout << A[0].height << endl; // 1 출력
공용체, union: 서로 다른 데이터형을 한 번에 한가지만 보관
union MyUnion
{
int intVal;
long longVal;
float floatVal;
};
MyUnion test;
test.intVal = 3;
test.longVal = 33;
test.floatVal = 3.3;
열거체, enum: 기호 상수를 만드는 방법
enum spectrum { red, orange=1, yellow, green, blue, violet, indigo, ultraviolet };
spectrum a = orange;
spectrum
을 새로운 데이터형 이름으로 만듬red, orange, yellow..
0에서부터 7까지 정수 값을 각각 나타내는 기호 상수로 만듬int b = blue; //blue = 4
b = blue + 3; //b = 7
C++ > 객체지향 프로그래밍
포인터: 사용할 주소에 이름을 붙인다
int* a, b;
int a = 6;
int* b;
b = &a;
cout << "a의 값 " << a << endl; //6
cout << "*b의 값 " << *b << endl; //6
cout << "a의 주소 " << &a << endl; //0033FAC0
cout << "*b의 값 " << b << endl; //0033FAC0
*b = *b + 1;
cout << "이제 a의 값은 " << a << endl; //7
return 0;
new 연산자 - 어던 데이터형을 원하는지 new 연산자에게 알려주면 new 연산자는 그에 알맞은 크기의 메모리 블록을 찾아내고 그 블록의 주소를 리턴
int* pointer = new int; //4 byte를 저장할 수 있는 주소를 찾아 pointer에 리턴
delete 연산자 - 사용한 메모리를 다시 메모리 풀로 환수
int* ps = new int; // 메모리 사용
delete ps;
double* p3 = new double[3]; //double형 데이터 3개를 저장할 수 있는 공간 대입
p3[0] = 0.2;
p3[1] = 0.5;
p3[2] = 0.8;
cout << "p3[1] is " << p3[1] << ".\n"; //0.5
p3 = p3 + 1; //포인터를 증가시킨다
cout << "Now p3[0] is " << p3[0] << " and "; //0.5
cout << "p3[1] is " << p3[1] << ".\n"; //0.8
char animal[20];
char* ps;
cout << "동물 이름을 입력하십시오\n";
cin >> animal;
ps = new char[strlen(animal)+1];
strcpy_s(ps, animal); // animal의 값을 ps에 복사
동적(dynamic) 구조체: 컴파일 시간이 아닌 실행 시간에 메모리를 대입받는 것
temp* ps = new temp;
struct MyStruct
{
char name[20];
int age;
};
int main()
{
using namespace std;
MyStruct* temp = new MyStruct;
cout <<"당신의 이름을 입력하십시오\n";
cin >> temp->name;
cout <<"당신의 나이를 입력하십시오\n";
cin >> (*temp).age;
}
->
로 표기