c++ const

本文详细介绍了C++中const关键字的使用方法及其应用场景,包括常量变量、指针、函数参数及返回类型、类的数据成员、类成员函数及对象等,并解释了mutable关键字的作用。

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

 

  • }

### C++ 中 `const` 关键字的用法及示例 #### 基础概念 `const` 是 C++ 中用于声明常量的关键字,它表示该变量或对象在其生命周期内不可被修改。通过使用 `const`,可以提高程序的安全性和可读性。 #### 定义常量 可以通过 `const` 来定义基本数据类型的常量。例如: ```cpp const int MAX_SIZE = 100; ``` 上述代码定义了一个整型常量 `MAX_SIZE`,其值为 100,在整个程序运行期间无法更改[^1]。 #### 指针中的 `const` 在指针中,`const` 可以修饰指针本身或者指针所指向的内容: 1. **只允许修改指针地址** 如果希望指针能够重新指向其他内存位置,而不能改变其所指向的数据,则可以这样写: ```cpp const int value = 7; int* p = (int*)&value; // 强制转换去掉 const 属性 ``` 2. **只允许修改指针所指向的内容** 若想让指针始终指向同一个地址,但能修改其中存储的数据,则应如下操作: ```cpp int a = 5; int b = 10; int* const ptr = &a; // ptr is constant pointer to an integer. *ptr = 8; // OK, modifies the content of 'a' // ptr = &b; // Error! Cannot change where 'ptr' points to ``` 3. **既不允许修改指针也不允许修改内容** 当需要保护指针及其指向的数据不发生任何变化时,需同时加上两个 `const`: ```cpp const char* const strPtr = "hello"; // Neither can we modify what strPtr points to nor reassign it elsewhere. ``` #### 非 `const` 转换为 `const` 有时为了函数调用兼容性等原因,可能需要将非 `const` 类型转化为 `const` 类型。这通常借助于强制类型转换完成,比如利用标准库提供的 `const_cast<>` 运算符实现: ```cpp #include <iostream> using namespace std; int main() { const int x = 7; int *p = const_cast<int*>(&x); cout << "*p = " << *p << endl; const char *buf = "abcdefghi"; char *rev = const_cast<char*>(buf); cout << "rev = " << rev << endl; } ``` 这里展示了如何把一个原本带有 `const` 特性的变量解封以便进一步处理[^2]。 #### 初始化 `const` 成员变量 当类中有某些成员应当保持不变时,可以在构造器初始化列表里设定它们的具体数值。这是因为一旦创建好这些字段之后就再无机会去调整了。 ```cpp class MyClass { public: explicit MyClass(int val): myConstMember(val){} private: const int myConstMember; }; ``` 此段落解释了即使是在复杂场景下仍然存在合理的方式来进行必要的设置工作[^3]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值