TUTORIAL: constante (const) Tipo

  • genux
  • Graduate
  • Graduate
  • Avatar de Usuario
  • Registrado: Ene 22, 2010
  • Mensajes: 106
  • Loc: UK
  • Status: Offline

Nota Enero 29th, 2010, 3:59 am

Introducción



Una constante (constante) significa que el tipo de variable (s) son de tipo constante y no puede ser alterada en el estado allí presentes. Usted puede const_cast su despegue y el tipo const y lo han hecho en el ejemplo de la clase.

Variables constantes



Hay par de lugares que usted puede poner el tipo de una variable const.

C Código: [ Select ]
[
int normalValue = 55;
const int constValue = 10;
 
  1. [
  2. int normalValue = 55;
  3. const int constValue = 10;
  4.  


El valor normal es de 55 años y puede ser alterado, pero la constValue es de 10 y no puede ser alterado, es bueno para un valor de pi por ejemplo.

Variables punteros constantes



Pueden ser punteros a tipos constantes, ya que puede apuntar a una variable constante y también se señaló el valor de un valor constante para que siempre apuntan a la misma variable.

Un puntero a una variable int constante, el valor del puntero se puede cambiar para que apunte a otra variable const int.
C Código: [ Select ]
const int * pConst= &constValue;
 
  1. const int * pConst= &constValue;
  2.  


Aquí es un puntero a una variable constante.
C Código: [ Select ]
int * const pConst2 = &normalValue;
 
  1. int * const pConst2 = &normalValue;
  2.  


Aquí es un puntero a un entero const con una variable constante.
C Código: [ Select ]
const int * const pConstConst = &constValue;
 
  1. const int * const pConstConst = &constValue;
  2.  

El puntero constante no puede ser alterada y también la ubicación pConstConst la memoria que se señaló constValue por ejemplo, no puede cambiar tampoco.

Funciones con las constantes



Las funciones también pueden tener tipos const asociadas a ellas, hay tres lugares diferentes,

C Código: [ Select ]
const int returnValue(const int value3) const
 
  1. const int returnValue(const int value3) const
  2.  


Con el fin de las constantes (const) dentro de la definición de la función
1. La const int retorno no puede ser alterado, puede alterar el valor si coloca el retorno en una variable diferente
2. El valor del parámetro no puede ser alterado.
3. Las variables dentro de la categoría "este" no puede ser alterado.

A continuación se muestra un ejemplo de lo anterior, he incluido el mensaje de error si intenta compilar el programa al violar el tipo const.

C Código: [ Select ]
#include <iostream>
 
using namespace std;
 
class constTest {
  private :
    int value;
  public:
    constTest() { value = 0;};
   
    int returnIntConst(int passingValue) const;
};
 
// cannot alter any value for the class variables e.g. value in this case.
// of course you could do a const_cast.. which takes off the constant (const) type
int constTest::returnIntConst(int passingValue) const
{
    // cannot alter any value inside the function
    // assignment of data-member ‘constTest::value’ in read-only structure
    // value = 3;
    const_cast<int&> (value) = passingValue; // take off the const type restriction
    return value;
}
 
int returnInt(const int value1)
{
  // cannot alter the parameter value1
  //error: assignment of read-only parameter ‘value1’
  // value1 = value1+ 2;
  return (value1 + 2);
}
 
// returning a constant value, which means that you cannot do anything to the
// returning value, but if you assign that value to another variable you can
const int returnConstInt(int value1)
{
    value1 = value1 + 2;
    return value1;
}
 
int main()
{
    // cannot alter the return value of the returnConstInt
    //  increment of read-only location ‘returnConstInt(3)’
    // int constValue = returnConstInt(3)++;
    int constValue = returnConstInt(3);
    // but you can alter the value of returning int from returnConstInt if passed to a variable
    constValue++;
    cout << constValue << endl;
   
    constTest cTest;
    cout << cTest.returnIntConst(10) << endl;
    return 0;
}
 
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class constTest {
  6.   private :
  7.     int value;
  8.   public:
  9.     constTest() { value = 0;};
  10.    
  11.     int returnIntConst(int passingValue) const;
  12. };
  13.  
  14. // cannot alter any value for the class variables e.g. value in this case.
  15. // of course you could do a const_cast.. which takes off the constant (const) type
  16. int constTest::returnIntConst(int passingValue) const
  17. {
  18.     // cannot alter any value inside the function
  19.     // assignment of data-member ‘constTest::value’ in read-only structure
  20.     // value = 3;
  21.     const_cast<int&> (value) = passingValue; // take off the const type restriction
  22.     return value;
  23. }
  24.  
  25. int returnInt(const int value1)
  26. {
  27.   // cannot alter the parameter value1
  28.   //error: assignment of read-only parameter ‘value1’
  29.   // value1 = value1+ 2;
  30.   return (value1 + 2);
  31. }
  32.  
  33. // returning a constant value, which means that you cannot do anything to the
  34. // returning value, but if you assign that value to another variable you can
  35. const int returnConstInt(int value1)
  36. {
  37.     value1 = value1 + 2;
  38.     return value1;
  39. }
  40.  
  41. int main()
  42. {
  43.     // cannot alter the return value of the returnConstInt
  44.     //  increment of read-only location ‘returnConstInt(3)’
  45.     // int constValue = returnConstInt(3)++;
  46.     int constValue = returnConstInt(3);
  47.     // but you can alter the value of returning int from returnConstInt if passed to a variable
  48.     constValue++;
  49.     cout << constValue << endl;
  50.    
  51.     constTest cTest;
  52.     cout << cTest.returnIntConst(10) << endl;
  53.     return 0;
  54. }
  55.  


y la salida sería

C Código: [ Select ]
6
10
 
  1. 6
  2. 10
  3.  


Conclusión



La constante (const) restringe el tipo de variables de ser modificada si no quieren que sean, ahorra posibles problemas si usted está tratando de modificar una variable que debe ser el mismo, por ejemplo pi .. no debe alterar 3,142 a 5.


Que yo hago realmente quieres hacer algún comentario con respecto a cualquier tutorial / post, contesta o PM me .. encantado de ayudar, mejor para compartir el conocimiento.
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Enero 29th, 2010, 3:59 am

Publicar Información

  • Total de mensajes en este tema: 1 mensaje
  • Moderador: Tutorial Writers
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 5 invitados
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC