static/dynamic cast

Posted sunchuankai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了static/dynamic cast相关的知识,希望对你有一定的参考价值。

#include <vector>
#include <iostream>

struct B
int m = 0;
void hello() const
std::cout << "Hello world, this is B!\n";

;
struct D : B
void hello() const
std::cout << "Hello world, this is D!\n";

;

enum class E ONE = 1, TWO, THREE ;
enum EU ONE = 1, TWO, THREE ;

int main()

// 1: initializing conversion
int n = static_cast<int>(3.14);
std::cout << "n = " << n << ‘\n‘;
std::vector<int> v = static_cast<std::vector<int>>(10);
std::cout << "v.size() = " << v.size() << ‘\n‘;

// 2: static downcast
D d;
B& br = d; // upcast via implicit conversion
br.hello();
D& another_d = static_cast<D&>(br); // downcast
another_d.hello();

// 3: lvalue to xvalue
std::vector<int> v2 = static_cast<std::vector<int>&&>(v);
std::cout << "after move, v.size() = " << v.size() << ‘\n‘;

// 4: discarded-value expression
static_cast<void>(v2.size());

// 5. inverse of implicit conversion
void* nv = &n;
int* ni = static_cast<int*>(nv);
std::cout << "*ni = " << *ni << ‘\n‘;

// 6. array-to-pointer followed by upcast
D a[10];
B* dp = static_cast<B*>(a);

// 7. scoped enum to int or float
E e = E::ONE;
int one = static_cast<int>(e);
std::cout << one << ‘\n‘;

// 8. int to enum, enum to another enum
E e2 = static_cast<E>(one);
EU eu = static_cast<EU>(e2);

// 9. pointer to member upcast
int D::*pm = &D::m;
std::cout << br.*static_cast<int B::*>(pm) << ‘\n‘;

// 10. void* to any type
void* voidp = &e;
std::vector<int>* p = static_cast<std::vector<int>*>(voidp);

————————————————

以上是关于static/dynamic cast的主要内容,如果未能解决你的问题,请参考以下文章

什么时候应该使用 static_cast、dynamic_cast、const_cast 和 reinterpret_cast?

const_cast,static_cast,dynamic_cast,reinterpret_cast的区别

static_cast, dynamic_cast, const_cast讨论

const_cast,static_cast,dynamic_cast,reinterpret_cast的区别(转)

static_castdynamic_castreinterpret_cast和const_cast

c++中四种cast转换分别是 ?