캐스팅 연산자는 C++에서 유형 캐스팅에 사용됩니다. 한 데이터 유형을 다른 데이터 유형으로 변환하는 데 사용됩니다. C++에서는 네 가지 유형의 캐스트를 지원합니다.
- static_cast
- 동적_캐스트
- const_cast
- 재해석_캐스트
1. 정적_캐스트
그만큼 static_cast 연산자는 C++에서 가장 일반적으로 사용되는 캐스팅 연산자입니다. 컴파일 타임 유형 변환을 수행하며 주로 컴파일러에서 안전하다고 간주되는 명시적 변환에 사용됩니다.
static_cast 구문
static_cast < new_type>(표현);>
어디,
- 표현: 변환할 데이터입니다.
- 새로운_유형: 원하는 표현 유형
static_cast를 사용하면 동일한 상속 계층 구조의 숫자 유형이나 포인터와 같은 관련 유형 간에 변환할 수 있습니다.
static_cast의 예
C++ // C++ program to illustrate the static_cast #include #include using namespace std; int main() { int num = 10; // converting int to double double numDouble = static_cast(숫자); // 데이터 유형 cout 인쇄<< typeid(num).name() << endl; // typecasting cout << typeid(static_cast(숫자)).이름()<< endl; // printing double type t cout << typeid(numDouble).name() << endl; return 0; }> 산출
i d d>
이 예에서는 다음을 포함했습니다. 유형 정보 우리가 사용할 수 있도록 도서관 유형ID() 데이터 유형을 확인하는 함수입니다. 정수 변수 'num'을 정의하고 static_cast를 사용하여 이를 double로 변환했습니다. 그런 다음 변수의 데이터 유형을 인쇄하고 전달합니다. static_cast(숫자) ~에 유형ID() 데이터 유형을 확인하는 함수입니다. 출력 i, d, d가 인쇄되는 것을 볼 수 있습니다. '나' 나타냅니다 정수 그리고 '디' 나타냅니다 더블 .
2. 동적_캐스트
그만큼 동적_캐스트 연산자는 주로 다운캐스팅(기본 클래스의 포인터/참조를 파생 클래스로 변환)을 수행하는 데 사용됩니다. 변환의 유효성을 확인하기 위해 런타임 검사를 수행하여 유형 안전성을 보장합니다.
Dynamic_cast의 구문
dynamic_cast < new_type>(표현);>
변환이 불가능한 경우, 동적_캐스트 반환합니다 널 포인터 (포인터 변환의 경우) 또는 던집니다. bad_cast 예외 (참조 변환용).
Dynamic_cast의 예
C++ // C++ program to illustrate the dynamic_cast #include using namespace std; // Base Class class Animal { public: virtual void speak() const { cout << 'Animal speaks.' << endl; } }; // Derived Class class Dog : public Animal { public: void speak() const override { cout << 'Dog barks.' << endl; } }; // Derived Class class Cat : public Animal { public: void speak() const override { cout << 'Cat meows.' << endl; } }; int main() { // base class pointer to derived class object Animal* animalPtr = new Dog(); // downcasting Dog* dogPtr = dynamic_cast(동물Ptr); // 타입 캐스팅이 성공했는지 확인합니다. if (dogPtr) { dogPtr->speak(); } else { cout<< 'Failed to cast to Dog.' << endl; } // typecasting to other dervied class Cat* catPtr = dynamic_cast(동물Ptr); if (catPtr) { catPtr->speak(); } else { cout<< 'Failed to cast to Cat.' << endl; } delete animalPtr; return 0; }> 산출
Dog barks. Failed to cast to Cat.>
설명: 출력의 첫 번째 줄이 인쇄됩니다. '동물Ptr' ~의 '동물' 유형이 성공적으로 캐스팅되었습니다. '개' 유형과 말하다() Dog 클래스의 함수가 호출되었지만 '동물' 에 입력 '고양이' 유형이 실패했습니다. '동물Ptr' 을 가리킨다 '개' 따라서 객체의 유형 캐스팅이 안전하지 않기 때문에 동적 캐스팅이 실패합니다.
라제쉬 칸나
3. const_cast
그만큼 const_cast 연산자는 변수의 const 또는 휘발성 한정자를 수정하는 데 사용됩니다. 이를 통해 프로그래머는 일시적으로 객체의 불변성을 제거하고 수정할 수 있습니다. const 객체를 수정하면 정의되지 않은 동작이 발생할 수 있으므로 const_cast를 사용할 때는 주의해야 합니다.
const_cast 구문
const_cast < new_type>(표현);>
const_cast의 예
C++ // C++ program to illustrate the const_cast #include using namespace std; int main() { const int number = 5; // Pointer to a const int const int* ptr = &number; // int* nonConstPtr = ptr; if we use this // instead of without using const_cast // we will get error of invalid conversion int* nonConstPtr = const_cast (포인트); *nonConstPtr = 10; 시합<< 'Modified number: ' << *nonConstPtr; return 0; }> 산출
Modified number: 10>
위의 예에서는 const 유형 한정자를 변경하여 포인터를 const 에게 비-상수 그런 다음 수정된 값을 인쇄합니다.
4. 재해석_캐스트
그만큼 reinterpret_cast 연산자 포인터를 다른 유형의 포인터로 변환하는 데 사용됩니다. 변환된 포인터가 동일한 유형인지 여부는 확인하지 않습니다.
reinterpret_cast 구문
reinterpret_cast < new_type>(표현);>
예
C++ // C++ program to illustrate the reinterpret_cast #include using namespace std; int main() { int number = 10; // Store the address of number in numberPointer int* numberPointer = &number; // Reinterpreting the pointer as a char pointer char* charPointer = reinterpret_cast(번호포인터); // 메모리 주소와 값을 인쇄합니다. cout<< 'Integer Address: ' << numberPointer << endl; cout << 'Char Address: ' << reinterpret_cast(문자 포인터)<< endl; return 0; }> 산출
Integer Address: 0x7fff64789f1c Char Address: 0x7fff64789f1c>
위의 예에서는 int 변수를 정의했습니다. '숫자' 그런 다음 '번호'의 주소를 저장합니다. '번호포인터' int 유형으로 변환한 후 '번호포인터' int 유형을 char 포인터에 넣은 다음 저장합니다. '문자 포인터' 변하기 쉬운. numberPointer와 charPointer의 주소가 모두 인쇄되었는지 확인합니다. charPointer에 저장된 주소를 출력하려면 재해석_캐스트 C++의 유형 검사 메커니즘을 우회하고 포인터가 유형별 해석 없이 일반 메모리 주소로 인쇄되도록 허용하는 데 사용됩니다.
메모: const_cast 및 reinterpret_cast는 다양한 종류의 오류에 취약하므로 일반적으로 권장되지 않습니다.