Tabbas, a nan yana tafiya:
A cikin duniyar shirye-shiryen C++, galibi kuna buƙatar canza nau'ikan. Juyawa na iya kasancewa daga nau'in bayanai mai sauƙi zuwa nau'in hadaddun, daga nau'in da aka samo asali zuwa ajin tushe, ko daga kowane nau'in da aka bayar zuwa kowane nau'in. C++ yana samar da hanyoyin yin simintin gyare-gyare guda huɗu don aiwatar da waɗannan juzu'ai: `static_cast`, `dynamic_cast`, `reinterpret_cast`, da simintin simintin salon C++. A cikin wannan labarin, za mu tattauna 'static_cast' dalla-dalla.
A cikin C++, 'Static_cast' ma'aikacin simintin gyare-gyaren lokaci ne. Ana amfani da shi musamman don jujjuya nau'ikan bayanan lambobi kamar canza 'biyu' zuwa 'int' ko 'int' zuwa 'float', da sauransu. Duk da haka, amfani da shi bai iyakance ga jujjuya nau'ikan bayanan lambobi kawai ba.
[h2] Fahimtar Simintin Tsaye [/h2]
Ma'anar 'static_cast' ita ce kamar haka:
static_cast < new_type > ( magana )
Nan, sabon_type shine nau'in da kuke son canza magana zuwa. Kalmomin na iya haɗawa da masu canji, na zahiri, ko maɗaukaki.
Bari mu bincika bayanin mataki-mataki na yadda `static_cast` ke aiki.
Da farko, muna buƙatar haɗa ɗakunan karatu a cikin lambar mu.
#include
Sa'an nan, a cikin babban aikinmu, bari mu ayyana madaidaicin lamba 'a' kuma mu sanya darajar 7 gareta. Bayan haka, muna ayyana madaidaicin 'b' don ya zama daidai da 22.0.
int babban () {
int a = 7;
yawo b = 22.0;
}
Bayan haka, muna amfani da `static_cast` don musanya waɗannan masu canji zuwa wani nau'in.
int babban () {
...
yawo c = static_cast
int d = static_cast
}
Anan, m 'a' na nau'in lamba an canza shi zuwa iyo kuma an sanya shi zuwa m'c'. Hakazalika, mabambanta 'b' nau'in float an canza shi zuwa lamba kuma an sanya shi zuwa madaidaicin 'd'. Mai aiki da 'static_cast' yana yin wannan jujjuyawar a lokacin tattarawa.
[h2] Kariya tare da static_cast [/ h2]
Kodayake `static_cast` na iya zama kamar kayan aiki mai ƙarfi, masu shirye-shirye suna buƙatar yin taka tsantsan yayin amfani da shi don jujjuya nau'in. Akwai manyan dalilai guda biyu akan haka:
- `static_cast` baya yin duba irin lokacin gudu. Wannan yana nufin cewa idan kayi ƙoƙarin canza nau'in da bai dace ba, ba zai jefa kuskure ba.
- Yin amfani da `static_cast` don juyar da ma'anar ajin tushe ko tunani zuwa ma'anar aji ko abin da aka samo, ba tare da tabbatar da abin aji cikakke ne na abin da aka samu ba, na iya haifar da kuskure.
Don taƙaitawa, `static_cast` ɗaya ne daga cikin masu yin simintin gyare-gyaren da C++ ke bayarwa, galibi ana amfani da su don canza nau'ikan bayanan lamba. Duk da haka, dole ne a kiyaye kada a yi amfani da shi ba daidai ba, saboda zai iya haifar da sakamakon da ba a so. Ta hanyar kiyaye waɗannan abubuwan a zuciya, zaku iya amfani da `static_cast` yadda ya kamata a cikin shirin ku na C++.