반응형


정적 캐스팅  static_cast  컴파일 타임에 잡아준다
 
 dynamic_cast 실행중에 잡아준다
 
 
static cast 의 경우 값 변환시 값을 유지할려고 한다(반올림 오차는 제외_, 이진수 표기는 달라질수 있음, ex 소수를 정수로 바구는 경우)
 
 컴파일 도중에 해준다 static cast 는 상속 관계만 따져서 상속관계에 있다면 컴파일 됨(실행중에는 문제가 생길수 있음)
 즉 완전 다른 상속관계의 캐스팅은 컴파일 에러를 벹는다
 실행도중 크래시 날수 있음
 변수형 체크 후 베이스 클래스를 파생 클래스로 변환시
 
 
 
 
 
 #include


class Animal
{
public:
Animal(){}

virtual void fn() {

}

private:

};

class Cat : public Animal
{
public:

private:

};

class Dog : public Animal
{
public:

private:

};

class AAA {

};


int main()
{

/*
정적 캐스팅
static_cast  컴파일 타임에 잡아준다

dynamic_cast 실행중에 잡아준다


static cast 의 경우 값 변환시 값을 유지할려고 한다(반올림 오차는 제외_, 이진수 표기는 달라질수 있음, ex 소수를 정수로 바구는 경우)

컴파일 도중에 해준다 static cast 는 상속 관계만 따져서 상속관계에 있다면 컴파일 됨(실행중에는 문제가 생길수 있음)
즉 완전 다른 상속관계의 캐스팅은 컴파일 에러를 벹는다
실행도중 크래시 날수 있음
변수형 체크 후 베이슼 ㅡㄹ래스를 파생 클래스로 변환시

*/


//static cast 로 값을 변할 할 경우 값을 유지하려고 한다 2진수 표기는 달라질 수 있음
int intVal = 30;
float fdd = static_cast(intVal); //컴파일 가능
char dd = static_cast(intVal); //컴파일 가능
//char* dd1 = static_cast<char*>(intVal); //컴파일 에러

Animal* animalCat = new Cat;
Cat* myCat = static_cast<Cat*>(animalCat);

Dog* ps = static_cast<Dog*>(animalCat); //static 은 상속관계만 따지기 때문에 에러가 안난다 animalCat 은 Animal 클래스를 부모로 두고 있는데 Dog 는 Animal 을 상속 받음으로, 그러나 위험함

//AAA* aaa = static_cast<AAA*>(animalCat); //상속관계가 없다면 컴파일 에러

//Dog* psd = dynamic_cast<Dog*>(animalCat); //이때는 컴파일 에러를 벹음

Dog* psd = dynamic_cast<Dog*>(animalCat); //!!!virtual 키워드가 없다면 이때는 컴파일 에러를 벹음
//, virtual 키워드가 있다면 컴파일 성공함, 그리고 null을 반환한다 
//dynamic cast 는 RTTI 가 켜 있어야 작동하는데 이것이 꺼져 있다면 static_cast 와 동일하게 동작한다



int b= 10;
int c = static_cast(b);
//unsigned int* c2 = static_cast(&b); //컴파일 에러
//unsigned int* c2 = reinterpret_cast(&b); //컴파일 가능
//int a = reinterpret_cast(b); //컴파일 에러
//Cat* catP = reinterpret_cast<Cat*>(&b); //컴파일 가능


/*
const_cast 는 (포인터의 상수성)만을 변경하고자 할때 사용한다!!!
값에는 안쓰이는데 값은 어차피 복사 되는거니깐 안전함
변수를 선언할 때 앞에 volatile을 붙이면 컴파일러는 해당 변수를 최적화에서 제외하여 항상 메모리에 접근하도록 만듭니다.

const_cast  로는 형을 바꿀 수는 없고 const 또는 volatile 애트리뷰트를 제거할때 사용한다
*/


//int iii = 30;
//const int ddd= const_cast(iii); //컴파일 에러

const int iii2 = 30;
//int ddd = const_cast(iii2); //컴파일 에러, 포인터가 아님
int* ddd = const_cast<int*>(&iii2); //컴파일 가능
const int* ddd3 = const_cast(&iii2); //컴파일 가능

int* tly = nullptr;
const int* ddd7 = const_cast(ddd); //컴파일 성공 const 를 붙여준다

//Animal* animalCat = new Cat;
//const Cat* myCat2 = static_cast(animalCat); //컴파일 가능
//const Cat* myCat2 = const_cast(animalCat); //const cast 는 형변환을 허용하지 않는다


return 0;
}

반응형

+ Recent posts