C++ 변수
- C++ 변수 선언
1) 키워드 이름으로 사용 불가
2) 숫자로 시작 불가
3) 특수문자는 _와 $만 사용 가능
4) 공백 포함 불가
5) 대소문자 구분 - 변수 : 4가지 속성
- 이름 : x
- 값 : 40
- 데이터타입(메모리크기) : 정수
- 메모리 주소
균일 초기화(uniform initialization)
- c++11 이후 부터, 대입 문법 대신 균일 초기화 사용을 권장
int a = 7
->int a {7}
byte 사용 시, 주의점
- C++17 이전
char
orunsigned char
을 통해 표현char a = 0123 // 8진수 char b = 0b111011 // 2진수
- c++17 이후 std::byte - cppreference.com
std::byte
를 통해 표현 (고정 1byte) <-<cstddef>
헤더- 산술 연산자 사용 불가
- 정수 타입이 아니기에 직접 대입 할당 및 비교 불가
// std::byte y = 1; // Error: cannot convert int to byte. std::byte y{1}; // OK // if (y == 13) {} // Error: cannot be compared. if (y == std::byte{13}) {} // OK, bytes are comparable // b *= 2; // Error: b is not of arithmetic type
숫자 경곗값
<limits>
의std::numeric_limits<type>
을 통해 해당 타입 경계값 파악 가능
캐스트
변수의 타입을 실행 중에 바꾸는 것
float myF {3.14f}; int i1 { (int)myF }; // c 방식 명시변환 int i2 { static_cast<int>(myF) } // c++ 권장 방식
업캐스팅
자식 클래스 객체를 부모 클래스 타입으로 변환하는 것
암시적 변환 처리 가능
다형성(polymorphism) 구현에 사용
class Animal { public: void speak() { std::cout << "Animal speaks" << std::endl; } }; class Dog : public Animal { public: void speak() { std::cout << "Dog barks" << std::endl; } }; Dog dog; Animal* animal = &dog; // 업캐스팅 animal->speak(); // Animal speaks
다운캐스팅
- 부모 클래스 객체를 자식 클래스 타입으로 변환하는 것
- 명시적으로 수행되어야 함
- 잘못된 다운캐스팅은 런타임 오류
- RTTI(Runtime Type Information) 사용
Animal* animal = new Dog(); Dog* dog = dynamic_cast<Dog*>(animal); if (dog) { dog->speak(); // Dog barks } else { std::cout << "다운캐스팅 실패" << std::endl; }
- RTTI(Runtime Type Information) 사용
부동소수점
- NaN 검증 :
std::isnan()
<-<cmath>
- Infinity 검증 :
std::isinf()
<-<cmath>
'공부 > C++' 카테고리의 다른 글
함수 (1) | 2025.03.03 |
---|---|
enum_class (0) | 2025.03.03 |
C++ 여러가지 기본 (0) | 2025.03.02 |
C++20: 모듈 선언 (0) | 2025.03.02 |
C++ 빌드 과정 (0) | 2025.03.02 |