개요
- static_cast
- const_cast
- as_const
- C++17
- const reference로 변환
- dynamic_cast
- 런타임에 다형성을 만족하는 파생 클래스 사이에서의 up/down cast
- reinterpret_cast
예제
- 코드
#include <cstdlib>
#include <iostream>
#include <string>
#include <typeinfo>
#include <utility>
using namespace std;
void func(string *s) {
*s += "1";
cout << "call func(string* s)" << endl;
}
void func(const string *s) { cout << "call func(const string* s)" << endl; }
void func(string &s) {
s += "1";
cout << "call func(string& s)" << endl;
}
void func(const string &s) { cout << "call func(const string& s)" << endl; }
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
public:
virtual ~Derived() {}
void show() { cout << 1 << endl; }
};
class Test1 {};
class Test2 {
public:
void show() { cout << 1 << endl; }
};
int main() {
int i = 1;
cout << typeid(static_cast<double>(i)).name() << endl;
const string s = "abc";
func(const_cast<string *>(&s));
cout << s << endl;
string ss = "abc";
func(const_cast<const string *>(&ss));
cout << ss << endl;
string sss = "abc";
func(as_const(sss));
cout << sss << endl;
func(sss);
cout << sss << endl;
Base *base = NULL;
Derived *derived = new Derived;
base = dynamic_cast<Base *>(derived);
derived = dynamic_cast<Derived *>(base);
derived->show();
delete derived;
base = NULL;
derived = NULL;
Test1 *t1 = NULL;
Test2 *t2 = new Test2;
t1 = reinterpret_cast<Test1 *>(t2);
t2 = reinterpret_cast<Test2 *>(t1);
t2->show();
delete t2;
t1 = NULL;
t2 = NULL;
return 0;
}
- 실행 결과
d
call func(string* s)
abc1
call func(const string* s)
abc
call func(const string& s)
abc
call func(string& s)
abc1
1
1