C++ Tutorial/Data Types/cast

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

A cast to float

<source lang="cpp">#include <iostream> using namespace std;

int main(){

 int i; 

 for(i=1; i <= 10; ++i ) 
   cout << i << "/ 2 is: " << (float) i / 2 << "\n"; 

 return 0; 

}</source>

1/ 2 is: 0.5
2/ 2 is: 1
3/ 2 is: 1.5
4/ 2 is: 2
5/ 2 is: 2.5
6/ 2 is: 3
7/ 2 is: 3.5
8/ 2 is: 4
9/ 2 is: 4.5
10/ 2 is: 5

Ambiguous function call when data type casting from int to char and unsigned char

<source lang="cpp">#include <iostream> using namespace std; char myfunc(unsigned char ch); char myfunc(char ch); int main() {

 cout << myfunc("c"); // this calls myfunc(char)
 //cout << myfunc(88) << " "; // ambiguous
 return 0;

} char myfunc(unsigned char ch) {

 return ch-1;

} char myfunc(char ch) {

 return ch+1;

}</source>

d"

Ambiguous function call when data type casting from int to double and float

<source lang="cpp">#include <iostream> using namespace std; float myfunc(float i); double myfunc(double i); int main() {

 cout << myfunc(10.1) << " "; // unambiguous, calls myfunc(double)
 //cout << myfunc(10); // ambiguous
 return 0;

} float myfunc(float i) {

 return i;

} double myfunc(double i) {

 return -i;

}</source>

-10.1 "

reinterpret_cast operator: cast from void * to unsigned *

<source lang="cpp">#include <iostream> using namespace std; int main() {

  unsigned x = 22, *unsignedPtr;
  void *voidPtr = &x;
  char *charPtr = "C++";
  // cast from void * to unsigned *
  unsignedPtr = reinterpret_cast< unsigned * >( voidPtr );
  cout << "*unsignedPtr is " << *unsignedPtr << "\ncharPtr is " << charPtr;
  return 0;

}</source>

reinterpret_cast operator: cast unsigned back to char *

<source lang="cpp">#include <iostream> using namespace std; int main() {

  unsigned x = 22, *unsignedPtr;
  void *voidPtr = &x;
  char *charPtr = "C++";
  // cast unsigned back to char *
  cout << "\nunsigned to char * results in: " << reinterpret_cast< char * >( x ) << endl;
  return 0;

}</source>

reinterpret_cast operator: use reinterpret_cast to cast a char * pointer to unsigned

<source lang="cpp">#include <iostream> using namespace std; int main() {

  unsigned x = 22, *unsignedPtr;
  void *voidPtr = &x;
  char *charPtr = "C++";
  // use reinterpret_cast to cast a char * pointer to unsigned
  cout << "\nchar * to unsigned results in: " << ( x = reinterpret_cast< unsigned >( charPtr ) );
  return 0;

}</source>

Using Explicit Casts

<source lang="cpp">#include <iostream> using std::cin; using std::cout; using std::endl; int main() {

 const long a = 3;
 const long b = 12;
 double c = 234.0;
 long d = 0;        
 long f = 0;         
 long g = 0;        
 d = static_cast<long>(c);
 f = static_cast<long>((c - d) * a);
 g = static_cast<long>(c * a * b)  b;
 cout << c << " \n "
      << d << " \n "
      << f << " \n "
      << g << " \n ";
 cout << endl;
 return 0;

}</source>

234
 234
 0
 0