const_cast in C++ | Geben Sie Casting-Operatoren ein

const_cast in C++ | Geben Sie Casting-Operatoren ein

C++ unterstützt die folgenden 4 Typen von Umwandlungsoperatoren:

1. const_cast
2. static_cast
3. dynamic_cast
4. reinterpret_cast

1. const_cast
const_cast wird verwendet, um die Konstanz von Variablen wegzuwerfen. Im Folgenden finden Sie einige interessante Fakten über const_cast.

1) const_cast kann verwendet werden, um Nicht-Konstanten-Klassenmember innerhalb einer Konstanten-Member-Funktion zu ändern. Betrachten Sie das folgende Code-Snippet. Innerhalb der const Member-Funktion fun() wird 'this' vom Compiler als 'const student* const this' behandelt, d. h. 'this' ist ein konstanter Zeiger auf ein konstantes Objekt, daher erlaubt der Compiler nicht, die Datenmember durch zu ändern 'dieser' Zeiger. const_cast ändert den Typ des „this“-Zeigers in „student* const this“.




#include <iostream> using namespace std;   class student { private :      int roll; public :      // constructor      student( int r):roll(r) {}        // A const function that changes roll with the help of const_cast      void fun() const      {          ( const_cast <student*> ( this ) )->roll = 5;      }        int getRoll()  { return roll; } };   int main( void ) {      student s(3);      cout << "Old roll number: " << s.getRoll() << endl;        s.fun();        cout << "New roll number: " << s.getRoll() << endl;        return 0; }

 

 

Ausgabe:

Old roll number: 3
New roll number: 5



2) const_cast kann verwendet werden, um const-Daten an eine Funktion zu übergeben, die const nicht empfängt. Beispielsweise erhält fun() im folgenden Programm einen normalen Zeiger, aber mit Hilfe von const_cast kann ein Zeiger auf eine Konstante übergeben werden.




#include <iostream> using namespace std;   int fun( int * ptr) {      return (*ptr + 10); }   int main( void ) {      const int val = 10;      const int *ptr = &val;      int *ptr1 = const_cast < int *>(ptr);      cout << fun(ptr1);      return 0; }

 

 

Ausgabe:

20



3) Es ist ein undefiniertes Verhalten, einen Wert zu ändern, der ursprünglich als const deklariert wurde. Betrachten Sie das folgende Programm. Die Ausgabe des Programms ist undefiniert. Die Variable „val“ ist eine konstante Variable und der Aufruf „fun(ptr1)“ versucht, „val“ mit const_cast zu modifizieren.




#include <iostream> using namespace std;   int fun( int * ptr) {      *ptr = *ptr + 10;      return (*ptr); }   int main( void ) {      const int val = 10;      const int *ptr = &val;      int *ptr1 = const_cast < int *>(ptr);      fun(ptr1);      cout << val;      return 0; }

 

 

Ausgabe:

 Undefined Behavior 

Es ist in Ordnung, einen Wert zu ändern, der ursprünglich nicht als const deklariert wurde. Wenn wir beispielsweise im obigen Programm const aus der Deklaration von val entfernen, erzeugt das Programm 20 als Ausgabe.




#include <iostream> using namespace std;   int fun( int * ptr) {      *ptr = *ptr + 10;      return (*ptr); }   int main( void ) {      int val = 10;      const int *ptr = &val;      int *ptr1 = const_cast < int *>(ptr);      fun(ptr1);      cout << val;      return 0; }

 

 



4) const_cast gilt als sicherer als einfaches Typcasting. Es ist sicherer in dem Sinne, dass das Gießen nicht stattfindet, wenn die Art des Gießens nicht mit dem ursprünglichen Objekt übereinstimmt. Beispielsweise schlägt die Kompilierung des folgenden Programms fehl, weil „int *“ in „char *“ umgewandelt wird




#include <iostream> using namespace std;   int main( void ) {      int a1 = 40;      const int * b1 = &a1;      char * c1 = const_cast < char *> (b1); // compiler error      *c1 = 'A' ;      return 0; }

 

 

Ausgabe:

prog.cpp: In function ‘int main()’:
prog.cpp:8: error: invalid const_cast from type 'const int*' to type 'char*'



5) const_cast kann auch verwendet werden, um flüchtige Attribute wegzuwerfen. Im folgenden Programm ist die Typ-ID von b1 beispielsweise PVKi (Zeiger auf eine flüchtige und konstante Ganzzahl) und die Typ-ID von c1 ist Pi (Zeiger auf Ganzzahl)




#include <iostream> #include <typeinfo> using namespace std;   int main( void ) {      int a1 = 40;      const volatile int * b1 = &a1;      cout << "typeid of b1 " << typeid (b1).name() << '\n' ;      int * c1 = const_cast < int *> (b1);      cout << "typeid of c1 " << typeid (c1).name() << '\n' ;      return 0; }

 

 

Ausgabe:

typeid of b1 PVKi
typeid of c1 Pi



Übung
Sagen Sie die Ausgabe der folgenden Programme voraus. Wenn es Kompilierungsfehler gibt, beheben Sie sie.

Frage 1




#include <iostream> using namespace std;   int main( void ) {      int a1 = 40;      const int * b1 = &a1;      char * c1 = ( char *)(b1);      *c1 = 'A' ;      return 0; }

 

 

Frage 2




#include <iostream> using namespace std;   class student { private :      const int roll; public :      // constructor      student( int r):roll(r) {}        // A const function that changes roll with the help of const_cast      void fun() const      {          ( const_cast <student*> ( this ) )->roll = 5;      }        int getRoll()  { return roll; } };   int main( void ) {      student s(3);      cout << "Old roll number: " << s.getRoll() << endl;        s.fun();        cout << "New roll number: " << s.getRoll() << endl;        return 0; }

 

 

– Aashish Barnwal. Bitte schreiben Sie Kommentare, wenn Sie etwas Falsches finden oder weitere Informationen zu dem oben besprochenen Thema teilen möchten