c++ const

来源:互联网 发布:nginx 跳转到二级目录 编辑:程序博客网 时间:2024/05/29 09:54

Constant is something that doesn't change. In C and C++ we use the keyword const to make program elements constant. const keyword can be used in many context in a C++program.

Const keyword can be used with:

 

Variables

Pointers

Function arguments and return types

Class Data members

Class Member functions

Objects

 

 

1)Constant Variables

 

If you make any variable as constant, using const keyword, you cannot change its value. Also,the constant variables must be initialized while declared.

 

  • int main
  • {
  •  const int i = 10;
  •  const int j = i+10;  // Works fine
  •  i++;    // This leads to Compile time error  
  • }

In this program we have made i as constant, hence if we try to change its value, compile time error is given. Though we can use it for substitution.

 

2)Pointers with Const

 

Pointers can be made const too. When we use const with pointers, we can do it in two ways, either we can apply const to what the pointer is pointing to, or we can make the pointer itself a const.

 

Pointer to Const

This means that the pointer is pointing to a const variable.

 

const int* u;

Here, u is a pointer that points to a const int. We can also write it like,

 

int const* v;

still it has the same meaning. In this case also, v is a pointer to an int which is const.

 

 

Const pointer

To make the pointer const, we have to put the const keyword to the right of the *.

 

  • int x = 1;
  • int* const w = &x;

 

Here, w is a pointer, which is const, that points to an int. Now we can't change the pointer but can change the value that it points to.

 

  • w++;  ---->compile error
  • (*w)++  ----> x will be 2

 

NOTE : We can also have a const pointer pointing to a const variable.

 

  • const int* const x;

 

 

3) const Function Arguments and Return types

 

We can make the return type or arguments of a function as const. Then we cannot change any of them.

 

  • void f(const int i)
  • {
  •  i++;    // Error
  • }

 

  • const int g()
  • {
  •  return 1;
  • }

 

Some important points to remember

For built in types, returning a const or non-const(not sure if it is true or not),doesn't make any difference.

 

  • const int h()
  • {
  •  return 1;
  • }
  • it main()
  • {
  •  const int j = h();
  •  int k = h();
  • }

Both j and k will be assigned 1. No error will occur.

 

For user defined data types, returning const, will prevent its modification, like a*b =c;

Temporary objects created while program execution are always of const type.

 

  • const char &get_val(string &str, string::size_type ix)
  • {
    • return str[ix];
  • }
  • int main()
  • {
    • string s("a test");
    • get_val(s,0) = 'A';  //compile error, can't modify const return value;

 

  • }

 

  • const int &getZero(vector<int> &a, int b)
  • {
    • return a[b];
  • }
  •   void main() {
  • ……..
  • getZero(v1,1) =3;  //also compile error, if define non-const getZero, v1[1] will change to 3

 

 

If a function has a non-const parameter, it cannot be passed a const argument while making a call.

 

void t(int*) { }

If we pass a const  int* argument, it will give error.

 

But, a function which has a const type parameter, can be passed a const type argument as well as a non-const argument.

 

void g(const int*){}

This function can have a int* as well as const int* type argument.

 

 

 

4) Const class Data members

 

These are data variables in class which are made const. They are not initialized during declaration. Their initialization occur in the

 constructor.

 

  • class X
  • {
    • private:
      • int ii;
      • const int kk;   --->new version support intialization now, const int kk = 5;
    • public:
    • // mutable int ii;
      • X(int x):kk(5)  // Constructor  ----->initialize jj to 5
      • { ii=x;}
  • }

 

In this program, kk is a const data member, in every object its independent copy is present, hence it is initialized with each object using constructor. Once initialized, it cannot be changed.

 

5) Const class Object

 

When an object is declared or created with const,  its data members can never be changed, during object's lifetime.

 

Syntax :

const class_nameobject;

Const class Memberfunction

 

const class will only call const member function :

  • const int i=5;
  • int k=5;
  • const int add1(const int& a)
  • const int add2( int& a) const
  •  
    • const int u = obj2.add2(i);        //compile error, i is const.
    • const int u = obj2.add2(k); //good, k is not const.
    • const int u = obj2.add1(k); // compile error, k is not const;
    • const int u = obj2.add1(i); //compile error, add1 is not const member function;
    • const int t = obj1.add1(k); //good;
    • const int u = obj1.add1(i); //good;
    • const int t = obj1.add2(k); //good;
    • const int u = obj1.add2(i); //compile error, i is const int;

 

 

6) A const member function never modifies data members in an object.

 

Syntax :

return_type function_name() const;

Example for const Object and const Member function

 

  • class X
  • {
  •  public:
  •  int i;
  •  X(int x)   // Constructor
  •  { i=x; }

 

  •  int f() const    // Constant function
  •  { return i; }   // const memeber function can't change data member like i++;

 

  •  int g()
  •  { i++; }

 

  •  int add(const int& x)
  •  { return(i+x); }
  • };

 

  • int main()
  • {
  • X obj1(10);          // Non const Object
  • const X obj2(20);   // Const Object

 

  • obj1.f();   // No error
  • obj2.f();   // No error

 

  • cout << obj1.i << obj2.i ; //output 10  20

 

  • obj1.g();   // No error
  • //obj2.g();   // Compile time error, const object can't call non-const member function
  • cout << obj1.i << obj2.i ;  // 11 20
  • const int i = 1;
  • int j= obj1.add(i);
  • int k = obj2.add(i);
  • cout << obj1.i << obj2.i<<"\n" ;  //11 20
  • cout <<j <<k<<"\n";  //12 21
  • }

 

Here,we can see, that const member function never changes data members of class, andit can be used with both const and

 non-const object, But a const object can't be used with a member function which tries to change its data members,

also only call const member function.

 

7)MutableKeyword

 

Mutable keyword is used with member variables of class, which we want to change even if the object is of const type. Hence,

 mutable data members of a const objects can be modified.

 

  •  class X
  • {
  •  public:
  •  mutable int i; //mutable, so can be changed by const member function;
  •  X(int x)   // Constructor
  •  { i=x; }

 

  •  int f() const   // Constant function
  •  { return i++; }   // good now, const memeber function can change mutable data member

 

  •  void  g()
  •  { i++; }

 

  •  int add(const int& x) const
  •  { return(i+x); }
  • };

 

  • int main()
  • {
  • X obj1(10);          // Non const Object
  • const X obj2(20);   // Const Object

 

  • obj1.f();   // No error
  • obj2.f();   // No error

 

  • cout << obj1.i << obj2.i<<"\n" ;  //output 11 21

 

  • obj1.g();   // No error
  • obj2.g();   // Compile time error, still can't call non-const member function;
  • cout << obj1.i << obj2.i<<"\n" ;  //output 12 21
  • const int i = 1;
  • int j= obj1.add(i); //ok, add must be const or non-const function
  • int k = obj2.add(i); //ok, add must be const  function
  • cout << obj1.i << obj2.i<<"\n" ;  //output 12 21
  • cout <<j <<k<<"\n";   //output: 13 22

 

  • }

0 0
原创粉丝点击