Conversion using Cast operator
ในภาษา C++ มีการเพิ่มคำสั่งสำหรับแปลงข้อมูล 4 แบบ คือ static_cast dynamic_cast reinterpret_cast และ const_cast เพื่อทำให้การแปลงมีประสิทธิภาพมากขึ้น
Static_cast
Static_cast ใช้ในการแปลงตัวแปรพื้นฐาน สามารถแปลง type ได้เหมือนกันกับ c-style และ function-style แต่ static_cast จะเกิด error เมื่อต้องการแปลงค่า address ประเภทหนึ่งไปยังตัวแปร pointor ประเภทอื่น ตัวอย่าง เช่น การแปลงค่า adress ประเภท char ไปเป็น int* ดังตัวอย่าง ที่2 แต่สามารถแปลง address ประเภทเดียวกันกับ pointor ไปเป็น pointor ได้
/*.................Ex. int converted to char type.....................*/
#include <iostream>
using namespace std;
int main() {
int num[2];
cin>>num[0]>>num[1]>>num[2];
cout<<" char C = "<< (char)num[0]<<" "<<(char)num[1] <<" "<<(char)num[2]<<endl;
// for(int i=0;i<3;i++){
// cin>>num[i];
// }
// cout<<"num = ";
// for(int j=0;j<3;j++){
// cout<<(char)num[j];
// }
//cout<<endl;
}#include <iostream>
using namespace std;
int main() {
int num[2];
for(int i=0;i<3;i++){
cin>>num[i];
}
cout<<"num = ";
for(int j=0;j<3;j++){
cout<<(char)num[j];
}
cout<<endl;
}จากตัวอย่างที่2 การใช้ static_cast โดยการแปลง ค่า address จาก ตัวแปร char ให้เป็นค่า int* จะไม่สามารถทำได้
Last updated
Was this helpful?