C スタイル キャストと /clr (C++/CLI)
次のトピックでは、共通言語ランタイムにのみ適用されます。
CLR を使用すると、コンパイラ、次の順序で、次に示すキャストの 1 に 15 C 形式のキャストをマップしようと入力します:
const_cast
safe_cast
const_cast と safe_cast
static_cast
const_cast と static_cast
キャストのいずれかが上の場合は有効一覧、および式とターゲットの種類は CLR 参照型の場合、 15 C 形式は、ランタイム チェック (castclass MSIL のプロセス)にマップをキャストします。は、 C. の式のキャストは無効、コンパイラ エラーと見なされます。
解説
C. の式のキャストはお勧めしません。を指定してコンパイル /clr (共通言語ランタイムのコンパイル)するときは、を使用します safe_cast (C++ コンポーネント拡張)。
次のサンプルは、. に const_castにマップされる式のキャストを示します。
// cstyle_casts_1.cpp
// compile with: /clr
using namespace System;
ref struct R {};
int main() {
const R^ constrefR = gcnew R();
R^ nonconstR = (R^)(constrefR);
}
次のサンプルは、. に safe_castにマップされる式のキャストを示します。
// cstyle_casts_2.cpp
// compile with: /clr
using namespace System;
int main() {
Object ^ o = "hello";
String ^ s = (String^)o;
}
次のサンプルは、. に const_castと safe_cast にマップされる式のキャストを示します。
// cstyle_casts_3.cpp
// compile with: /clr
using namespace System;
ref struct R {};
ref struct R2 : public R {};
int main() {
const R^ constR2 = gcnew R2();
try {
R2^ b2DR = (R2^)(constR2);
}
catch(InvalidCastException^ e) {
System::Console::WriteLine("Invalid Exception");
}
}
次のサンプルは、. に static_castにマップされる式のキャストを示します。
// cstyle_casts_4.cpp
// compile with: /clr
using namespace System;
struct N1 {};
struct N2 {
operator N1() {
return N1();
}
};
int main() {
N2 n2;
N1 n1 ;
n1 = (N1)n2;
}
次のサンプルは、. に const_castと static_cast にマップされる式のキャストを示します。
// cstyle_casts_5.cpp
// compile with: /clr
using namespace System;
struct N1 {};
struct N2 {
operator const N1*() {
static const N1 n1;
return &n1;
}
};
int main() {
N2 n2;
N1* n1 = (N1*)(const N1*)n2; // const_cast + static_cast
}
次のサンプルは、. にランタイム チェックにマップされる式のキャストを示します。
// cstyle_casts_6.cpp
// compile with: /clr
using namespace System;
ref class R1 {};
ref class R2 {};
int main() {
R1^ r = gcnew R1();
try {
R2^ rr = ( R2^)(r);
}
catch(System::InvalidCastException^ e) {
Console::WriteLine("Caught expected exception");
}
}
次のサンプルでは、コンパイラはエラーを発行無効な 15 C 形式のキャストを示します。
// cstyle_casts_7.cpp
// compile with: /clr
using namespace System;
int main() {
String^s = S"hello";
int i = (int)s; // C2440
}
要件
コンパイラ オプション: /clr