logo

C++ での型キャスト

このセクションでは、C++ プログラミング言語における変数の型キャストについて説明します。型キャストとは、プログラム内での 1 つのデータ型から別のデータ型への変換を指します。型キャストは 2 つの方法で実行できます。1 つはコンパイラによる自動、もう 1 つはプログラマまたはユーザーによる手動です。型キャストは型変換とも呼ばれます。

C++ での型キャスト

たとえば、指定されたデータが整数型であり、それを浮動小数点数型に変換するとします。したがって、int データを float 型に手動でキャストする必要があります。このタイプのキャストは、C++ では型キャストと呼ばれます。

 int num = 5; float x; x = float(num); x = 5.0 

2nd例:

 float num = 5.25; int x; x = int(num); Output: 5 

型キャストは、暗黙的変換または暗黙的型キャストと、明示的型変換または明示的型キャストの 2 つのタイプに分類されます。

暗黙的な型キャストまたは暗黙的な型変換

  • これは自動活字鋳造として知られています。
  • プログラマやユーザーなどの外部介入を必要とせずに、あるデータ型から別のデータ型に自動的に変換されます。これは、コンパイラがあるデータ型を別のデータ型に自動的に変換することを意味します。
  • すべてのデータ型は、情報を失うことなく最大の型に自動的にアップグレードされます。
  • 両方の変数が相互に互換性がある場合にのみ、プログラムに適用できます。
 char - sort int -> int -> unsigned int -> long int -> float -> double -> long double, etc. 

注: 暗黙的な型キャストは、低いデータ型から高いデータ型に向かって実行する必要があります。そうしないと、基本的なデータ型に影響を及ぼし、精度やデータが失われる可能性があり、コンパイラがこの影響について警告を表示する可能性があります。

C++ で暗黙的な型キャストを使用するプログラム

C++ の暗黙的な型キャストを使用して、ある変数を別の変数にキャストする例を作成してみましょう。

 #include using namespace std; int main () { short x = 200; int y; y = x; cout << ' Implicit Type Casting ' << endl; cout << ' The value of x: ' << x << endl; cout << ' The value of y: ' << y << endl; int num = 20; char ch = 'a'; int res = 20 + 'a'; cout << ' Type casting char to int data type ('a' to 20): ' << res << endl; float val = num + 'A'; cout << ' Type casting from int data to float type: ' << val << endl; return 0; } 

出力:

 Implicit Type Casting The value of x: 200 The value of y: 200 Type casting char to int data type ('a' to 20): 117 Type casting from int data to float type: 85 

上記のプログラムでは、short データ型の変数 x が 200 であり、整数変数 y を宣言しました。その後、x 値を y に代入すると、コンパイラーは短いデータ値 x を y に自動的に変換し、y が 200 であることを返します。

マークダウン取り消し線

次の式では、int 型変数 num を 20、character 型変数 ch を 'a' (整数値 97 に相当) と宣言しました。次に、これら 2 つの変数を追加して暗黙的な変換を実行します。式の結果は 117 を返します。

同様に、3 番目の式では、整数変数 num が 20、文字変数 ch が 65 を加算し、その結果を浮動小数点数変数 val に代入します。したがって、式の結果はコンパイラによって自動的に float 型に変換されます。

明示的な型キャストまたは明示的な型変換

  • これは、プログラム内の手動タイプ キャストとも呼ばれます。
  • プログラム内のあるデータ型から別のデータ型に変更するには、プログラマまたはユーザーが手動でキャストします。これは、ユーザーがプログラムの要件に従って、あるデータを別のデータに簡単にキャストできることを意味します。
  • 変数の互換性をチェックする必要はありません。
  • このキャストでは、プログラム内のある変数のデータ型を別の変数にアップグレードまたはダウングレードできます。
  • Cast () 演算子を使用して変数の型を変更します。

明示的な型キャストの構文

 (type) expression; 

タイプ: これは、指定された式を変換するユーザー定義データを表します。

表現: データ型が変換される定数値、変数、または式を表します。

たとえば、浮動小数点数値が 4.534 で、整数値を変換するには、ステートメントは次のようになります。

 int num; num = (int) 4.534; // cast into int data type cout << num; 

上記のステートメントが実行されると、浮動小数点値は Cast () 演算子を使用して整数データ型にキャストされます。また、float 値は、小数部分を切り捨て、整数値として 4 のみを表示する整数に割り当てられます。

C++ での明示的な型キャストの使用をデモするプログラム

C++ プログラミング言語の明示的な型キャストを使用して、ある型変数を別の型にキャストする簡単なプログラムを作成してみましょう。

サルマン・カーンの年齢
 #include using namespace std; int main () { // declaration of the variables int a, b; float res; a = 21; b = 5; cout << ' Implicit Type Casting: ' << endl; cout << ' Result: ' << a / b << endl; // it loses some information cout << ' 
 Explicit Type Casting: ' << endl; // use cast () operator to convert int data to float res = (float) 21 / 5; cout << ' The value of float variable (res): ' << res << endl; return 0; } 

出力:

 Implicit Type Casting: Result: 4 Explicit Type Casting: The value of float variable (res): 4.2 

上記のプログラムでは、値が 21 と 2 である 2 つの整数変数 a と b を取得します。次に、a を b (21/2) で除算すると、4 の int 型の値が返されます。

2 番目の式では、明示的な型キャスト メソッドのキャスト演算子を使用して、データを失わずに a と b の結果を格納する float 型変数 res を宣言します。

キャスト演算子を使用してdoubleデータをint型とfloat型にキャストするプログラム

C++ プログラミングで double データを float 型と int 型にキャストして四角形の面積を取得する例を考えてみましょう。

 #include using namespace std; int main () { // declaration of the variables double l, b; int area; // convert double data type to int type cout << ' The length of the rectangle is: ' <> l; cout << ' The breadth of the rectangle is: ' <> b; area = (int) l * b; // cast into int type cout << ' The area of the rectangle is: ' << area << endl; float res; // convert double data type to float type cout << ' 
 
 The length of the rectangle is: ' << l << endl; cout << ' The breadth of the rectangle is: ' << b << endl; res = (float) l * b; // cast into float type cout << ' The area of the rectangle is: ' << res; return 0; } 

出力:

 The length of the rectangle is: 57.3456 The breadth of the rectangle is: 12.9874 The area of the rectangle is: 740 The length of the rectangle is: 57.3456 The breadth of the rectangle is: 12.9874 The area of the rectangle is: 744.77 

型キャストのいくつかの異なるタイプ

型キャストには、プログラムのニーズに応じて、あるデータ型を別のデータ型に強制的に変換するキャスト演算子があります。 C++ には、次の 4 つの異なるタイプのキャスト演算子があります。

  1. 静的キャスト
  2. ダイナミックキャスト
  3. const_cast
  4. 再解釈_キャスト

静的キャスト:

static_cast は、あるデータ型を別のデータ型に変換またはキャストする単純なコンパイル時キャストです。これは、実行時に実行されたキャストが有効かどうかのデータ型をチェックしないことを意味します。したがって、プログラマまたはユーザーは、変換が安全かつ有効であることを確認する責任があります。

static_cast は、暗黙的なキャストによって実行されるすべての変換を実行できる十分な機能を備えています。また、相互に関連するクラスのポインタ間の変換も実行します (アップキャスト - > 派生クラスから基底クラスへ、またはダウンキャスト - > 基底クラスから派生クラスへ)。

静的キャストの構文

 static_cast (expression); 

Static Cast の使用法をデモンストレーションするプログラム

C++ プログラミングで型キャストの静的キャストを使用する簡単な例を作成してみましょう。

 #include using namespace std; int main () { // declare a variable double l; l = 2.5 * 3.5 * 4.5; int tot; cout << ' Before using the static cast:' << endl; cout << ' The value of l = ' << l << endl; // use the static_cast to convert the data type tot = static_cast (l); cout << ' After using the static cast: ' << endl; cout << ' The value of tot = ' << tot << endl; return 0; } 

出力:

 Before using the static cast: The value of l = 39.375 After using the static cast: The value of tot = 39 

ダイナミックキャスト

Dynamic_cast は、クラス ポインターと参照に対してのみ、ある型変数から別の型変数への変換を実行するために使用されるランタイム キャスト演算子です。これは、実行時に変数の有効なキャストをチェックし、キャストが失敗した場合は NULL 値を返すことを意味します。動的キャストは RTTI (Runtime Type Identification) メカニズムに基づいています。

C++ での Dynamic Cast の使用法をデモンストレーションするプログラム

C++ プログラミング言語で Dynamic_cast を実行する簡単なプログラムを作成してみましょう。

 #include using namespace std; class parent { public: virtual void print() { } }; class derived: public parent { }; int main () { // create an object ptr parent *ptr = new derived; // use the dynamic cast to convert class data derived* d = dynamic_cast (ptr); // check whether the dynamic cast is performed or not if ( d != NULL) { cout << ' Dynamic casting is done successfully'; } else { cout << ' Dynamic casting is not done successfully'; } } 

出力:

 Dynamic casting is done successfully. 

キャスト型の再解釈

reinterpret_cast 型キャストは、指定されたポインタが互いに属しているかどうかに関係なく、ポインタを他の型のポインタにキャストするために使用されます。これは、ポインタまたはポインタが指すデータが同一で​​あるかどうかをチェックしないことを意味します。また、ポインタを整数型にキャストしたり、その逆も行います。

reinterpret_cast 型の構文

 reinterpret_cast expression; 

C++ で再解釈キャストを使用するプログラム

C++ 言語での再解釈を使用したポインターの変換を示すプログラムを作成してみましょう。

 #include using namespace std; int main () { // declaration of the pointer variables int *pt = new int (65); // use reinterpre_cast operator to type cast the pointer variables char *ch = reinterpret_cast (pt); cout << ' The value of pt: ' << pt << endl; cout << ' The value of ch: ' << ch << endl; // get value of the defined variable using pointer cout << ' The value of *ptr: ' << *pt << endl; cout << ' The value of *ch: ' << *ch << endl; return 0; } 

出力:

 The value of pt: 0x5cfed0 The value of ch: A The value of *ptr: 65 The value of *ch: A 

定数キャスト

const_cast は、ソース ポインタの const 動作を変更または操作するために使用されます。これは、const ポインターを非 const ポインターに設定する方法と、const ポインターから const を削除または除去する方法の 2 つの方法で const を実行できることを意味します。

Const Cast型の構文

Javaのプログラム
 const_cast exp; 

C++ で Const Cast を使用するプログラム

C++ の const_cast を使用して、ソース ポインターを非キャスト ポインターにキャストするプログラムを作成してみましょう。

 #include using namespace std; // define a function int disp(int *pt) { return (*pt * 10); } int main () { // declare a const variable const int num = 50; const int *pt = # // get the address of num // use const_cast to chnage the constness of the source pointer int *ptr = const_cast (pt); cout << ' The value of ptr cast: ' << disp(ptr); return 0; } 

出力:

 The value of ptr cast: 500