C++ Tutorial/Data Types/const cast

Материал из C\C++ эксперт
Версия от 13:31, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Cast parameter with const_cast

<source lang="cpp">void g(char* str) { } void f(const char* str) {

 g(const_cast<char*>(str));

} int main(int argc, char** argv) {

 char str[100];
 f(str);
 return (0);

}</source>

const_cast char type

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <cstring>
  2. include <cctype>

const char *maximum( const char *first, const char *second ) {

  return ( strcmp( first, second ) >= 0 ? first : second );

} int main() {

  char s1[] = "h";
  char s2[] = "g";
  char *maxPtr = const_cast< char * >( maximum( s1, s2 ) );
  cout << "The larger string is: " << maxPtr << endl;
  return 0;
  

}</source>

The larger string is: h

const_cast int value

<source lang="cpp">#include <iostream> using namespace std; void sqrval(const int *val) {

 int *p;
 // cast away const-ness.
 p = const_cast<int *> (val);
 *p = *val * *val; // now, modify object through v

} int main() {

 int x = 10;
 cout << "x before call: " << x << endl;
 sqrval(&x);
 cout << "x after call: " << x << endl;
 return 0;

}</source>

x before call: 10
x after call: 100

Use const_cast on a const reference

<source lang="cpp">#include <iostream> using namespace std; void sqrval(const int &val) {

 const_cast<int &> (val) = val * val;

} int main() {

 int x = 10;
 cout << "x before call: " << x << endl;
 sqrval(x);
 cout << "x after call: " << x << endl;
 return 0;

}</source>

x before call: 10
x after call: 100

Use const_cast to cast parameter before passing it into a function

<source lang="cpp">#include <iostream> using namespace std; void print (char * str) {

 cout << str << endl;

} int main () {

 const char * c = "sample text";
 print ( const_cast<char *> (c) );
 return 0;

}</source>