C++ Tutorial/Development/static cast

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Use static_cast.

#include <iostream>
using namespace std;
int main()
{
  int i;
  for(i=0; i<10; i++)
    cout << static_cast<double> (i) / 3 << " ";
  return 0;
}
0 0.333333 0.666667 1 1.33333 1.66667 2 2.33333 2.66667 3 "

Using static_cast: base and derived class

#include <iostream>
#include <ostream>
class base {};
class derived : public base {};
class other : public base {};
int main()
{
  base* b = new derived;
  static_cast<derived&>(*b); 
  static_cast<other*>(b);    
  derived* d = new derived;
  b = d;
  b = static_cast<base*>(d); 
}

Using static_cast: for enum data type

#include <iostream>
#include <ostream>
enum color   { red, black };
int main()
{
  color c = static_cast<color>(red);
}