16. C++의 형 변환 연산자
출처: 윤성우 열혈강의 C++ 예제코드
16.1. C++에서의 형 변환 연산
- dynamic_cast: 상속관계에서 안전한 형 변환
#include <iostream>
using namespace std;
class Car
{
private:
int fuelGauge;
public:
Car(int fuel) : fuelGauge(fuel)
{ }
void ShowCarState()
{
cout<<"잔여 연료량: "<<fuelGauge<<endl;
}
};
class Truck : public Car
{
private:
int freightWeight;
public:
Truck(int fuel, int weight)
: Car(fuel), freightWeight(weight)
{ }
void ShowTruckState()
{
ShowCarState();
cout<<"화물의 무게: "<<freightWeight<<endl;
}
};
int main(void)
{
Car * pcar1=new Truck(80, 200);
Truck * ptruck1=dynamic_cast<Truck*>(pcar1); // 컴파일 에러
Car * pcar2=new Car(120);
Truck * ptruck2=dynamic_cast<Truck*>(pcar2); // 컴파일 에러
Truck * ptruck3=new Truck(70, 150);
Car * pcar3=dynamic_cast<Car*>(ptruck3); // 컴파일 OK!
return 0;
}
- static_cast: A 타입에서 B타입으로
#include <iostream>
using namespace std;
class Car
{
private:
int fuelGauge;
public:
Car(int fuel) : fuelGauge(fuel)
{ }
void ShowCarState()
{
cout<<"잔여 연료량: "<<fuelGauge<<endl;
}
};
class Truck : public Car
{
private:
int freightWeight;
public:
Truck(int fuel, int weight)
: Car(fuel), freightWeight(weight)
{ }
void ShowTruckState()
{
ShowCarState();
cout<<"화물의 무게: "<<freightWeight<<endl;
}
};
int main(void)
{
Car * pcar1=new Truck(80, 200);
Truck * ptruck1=static_cast<Truck*>(pcar1); // 컴파일 OK!
ptruck1->ShowTruckState();
cout<<endl;
Car * pcar2=new Car(120);
Truck * ptruck2=static_cast<Truck*>(pcar2); // 컴파일 OK! 그러나!
ptruck2->ShowTruckState();
return 0;
}
- const_cast: const의 성향을 삭제
#include <iostream>
using namespace std;
void ShowString(char* str)
{
cout<<str<<endl;
}
void ShowAddResult(int& n1, int& n2)
{
cout<<n1+n2<<endl;
}
int main(void)
{
const char * name="Lee Sung Ju";
ShowString(const_cast<char*>(name));
const int& num1=100;
const int& num2=200;
ShowAddResult(const_cast<int&>(num1), const_cast<int&>(num2));
return 0;
}
- reinterpret_cast: 상관없는 자료형으로 형 변환
#include <iostream>
using namespace std;
int main(void)
{
int num=0x010203;
char * ptr=reinterpret_cast<char*>(&num);
for(int i=0; i<sizeof(num); i++)
cout<<static_cast<int>(*(ptr+i))<<endl;
return 0;
}