have to do_yeon

[C++ / OOP_lec03] C part in C++ (2) 본문

Supplementary/OOP (1-2)

[C++ / OOP_lec03] C part in C++ (2)

또김또 2022. 9. 27. 00:32


1. string (문자열)

 

헤더파일 : <iostream>

string (문자열) = char (문자) 의 집합.

따라서 string (문자열) 의 각각 글자를 char (문자)로 분리 가능하다.

#include <iostream>
#include <string>

using namespace std;

int main() {
	string s = "Hello World!";
	char c = s[1];

	cout << c;	// e
}

 

영어는 한 글자당 1byte 이지만 한글은 아니다. CP949에서 기본적으로는 2bytes 인데, 우리에게 필요한 부분은 아닌 것 같으니 각설하고, UTF-8로 인코딩 했을 때 3bytes임을 기억하면 된다.

#include <iostream>
#include <string>
#include <Windows.h>	// To use SetConsoleOutputCP

using namespace std;

int main(){
    // Change console code page to UFT-8.
    // (The default code page of console is CP949)
    SetConsoleOutputCP(CP_UTF8);
    
    string greeting = u8"안녕하세요!";
    
    cout << greeting << endl;	// 안녕하세요!
    cout << greeting.size() << endl;	// 16
    
    return 0;
}

 

예제를 보면 느낌표와 같은 특수문자는 1byte 임을 알 수 있다.

 


2. Constant (상수)

 

말 그대로 상수이다. const로 정의되면 그 값을 바꿀 수 없다.

#include <iostream>

using namespace std;

int main(){
    const int a = 3;
    int b = 5;
    
    a = 10;	// Error! We cannot modify constant.
    b = 7;
    b = a;
    
    return 0;
}

 


3. auto

 

C++11 이후부터 데이터타입 auto가 생겼다! 말 그대로 자동으로 데이터타입을 지정해준다.

auto a = 3;	// int
auto b = 3.13f;	// float

 

C++14부터 지원하기 시작하는 auto의 template기능이다.

#include <iostream>

using namespace std;

/* ex) template
template<typename T>
T add(T a, T b) {
    return a + b;
}
*/

auto add(auto a, auto b) {
    return a + b;
}

int main() {
    auto result = add(3, 5);
    cout << result;	// 8
    
    return 0;
}

이게 가능하다니 auto는 신이야!!!!

 

하지만 남용하지 말자... 어차피 나중에 복잡한 과정에서 코드를 짜게 되면 변수선언이 매우 중요해지기 때문에 auto 떡칠하다간 꼬일 수 있다..!!

 


4. Operator (연산자)

 

C에서 사용하던 연산자 모두 사용 가능하다. 당연히 연산 순서는 사칙연산 순서이다.

 

참고 >> https://en.cppreference.com/w/cpp/language/operator_precedence 

 

C++ Operator Precedence - cppreference.com

The following table lists the precedence and associativity of C++ operators. Operators are listed top to bottom, in descending precedence. ↑ The operand of sizeof can't be a C-style type cast: the expression sizeof (int) * p is unambiguously interpreted

en.cppreference.com

 

Comments