1. 程式人生 > 其它 >C++ 型別轉換

C++ 型別轉換

隱式型別轉換 Implicit conversion

  • Standard conversions affect fundamental data types, and allow conversions such as the conversions between 1)numerical types (short to int, int to float, double to int...), 2)to or from bool, and 3)some pointer conversions.
  • Some of these conversions may imply** a loss of precision**, which the compiler can signal with a warning. This warning can be avoided with an explicit conversion
    .
  • Implicit conversions also include 4)constructor or 5)operator conversions, which affect classes that include specific constructors or operator functions to perform conversions.
class A {};
class B { public: B (A a) {} };

A a;
B b=a;

顯式型別轉換 Explicit conversion

  • C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functiona
    l and c-like casting:
short a=2000;
int b;
b = (int) a;    // c-like cast notation
b = int (a);    // functional notation 
  • These explicit conversion operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors
    . For example, the following code is syntactically correct:
// class type-casting
#include <iostream>
using namespace std;

class CDummy {
    float i,j;
};

class CAddition {
	int x,y;
  public:
	CAddition (int a, int b) { x=a; y=b; }
	int result() { return x+y;}
};

int main () {
  CDummy d;
  CAddition * padd;
  padd = (CAddition*) &d;
  cout << padd->result();
  return 0;
}