모든 종류의 형변환을 수행할 수 있지만, C++에서는 보다 안전한 캐스트를 권장합니다.
#include <iostream>
int main() {
int a = 10;
double b = (double)a;
std::cout << "C-style cast: " << b << std::endl;
return 0;
}
컴파일 시간에 검사되는 일반적인 캐스트입니다.
#include <iostream>
int main() {
int a = 10;
double b = static_cast<double>(a);
std::cout << "static_cast: " << b << std::endl;
return 0;
}
런타임에 타입 정보를 사용하여 안전하게 다운캐스팅을 수행합니다.
#include <iostream>
class Base {
public:
virtual void foo() {}
};
class Derived : public Base {};
int main() {
//업 캐스팅
Base* basePtr = new Derived;
//다운 캐스팅
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
std::cout << "dynamic_cast successful." << std::endl;
} else {
std::cout << "dynamic_cast failed." << std::endl;
}
delete basePtr;
return 0;
}
const를 추가하거나 제거하는데 사용됩니다.
#include <iostream>
int main() {
const int x = 5;
int y = const_cast<int&>(x);
std::cout << "const_cast: " << y << std::endl;
return 0;
}
매우 강력한 캐스트로, 서로 다른 형식 간의 포인터나 참조를 변환할 때 사용됩니다.
#include <iostream>
int main() {
int* ptr = new int(42);
long long int ptrValue = reinterpret_cast<long long int>(ptr);
std::cout << "reinterpret_cast: " << ptrValue << std::endl;
delete ptr;
return 0;
}
C++11 이후 도입된 형식 추론 기능으로, 변수 선언 시 자동으로 형식을 추론합니다.
#include <iostream>
int main() {
auto x = 3.14;
std::cout << "auto: " << x << std::endl;
return 0;
}
주어진 표현식의 형식을 추론합니다.
#include <iostream>
int main() {
int a = 5;
double b = 3.14;
decltype(a + b) result = a + b;
std::cout << "decltype: " << result << std::endl;
return 0;
}