美文网首页
const 关键字的学习

const 关键字的学习

作者: yanlong107 | 来源:发表于2020-07-15 20:03 被阅读0次

一、const 修饰普通类型的变量

const int  a = 7; 
int  b = a; // 正确
a = 8;       // 错误,不能改变

a 被定义为一个常量,并且可以将 a 赋值给 b,但是不能给 a 再次赋值。对一个常量赋值是违法的事情,因为 a 被编译器认为是一个常量,其值不允许修改。

二、const 修饰指针变量

1. const 修饰指针指向的内容,则内容为不可变量

const int *p = 8;

指针指向的内容 8 不可改变。简称左定值,因为 const 位于 * 号的左边

2. const 修饰指针,则指针为不可变量

int a = 8;
int* const p = &a;
*p = 9; // 正确
int  b = 7;
p = &b; // 错误

对于 const 指针 p 其指向的内存地址不能够被改变,但其内容可以改变。简称,右定向。因为 const 位于 * 号的右边

3. const 修饰指针和指针指向的内容,则指针和指针指向的内容都为不可变量

int a = 8;
const int * const  p = &a;

这时,const p 的指向的内容和指向的内存地址都已固定,不可改变

三、const 修饰传递参数

1. 值传递的 const 修饰传递,一般这种情况不需要 const 修饰,因为函数会自动产生临时变量复制实参值

#include<iostream>
 
using namespace std;
 
void Cpf(const int a)
{
    cout<<a;
    // ++a;  是错误的,a 不能被改变
}
 
int main(void)
 
{
    Cpf(8);
    system("pause");
    return 0;
}

2. const 参数为指针时,可以防止指针被意外篡改

#include<iostream>
 
using namespace std;
 
void Cpf(int *const a)
{
    cout<<*a<<" ";
    *a = 9;
}
 
int main(void)
{
    int a = 8;
    Cpf(&a);
    cout<<a; // a 为 9
    system("pause");
    return 0;
}

三、const 修饰类成员函数

const 修饰类成员函数,其目的是防止成员函数修改被调用对象的值,如果我们不想修改一个调用对象的值,所有的成员函数都应当声明为 const 成员函数。
下面的 get_cm()const; 函数用到了 const 成员函数:

#include<iostream>
 
using namespace std;
 
class Test
{
public:
    Test(){}
    Test(int _m):_cm(_m){}
    int get_cm()const
    {
       return _cm;
    }
 
private:
    int _cm;
};
 
 
 
void Cmf(const Test& _tt)
{
    cout<<_tt.get_cm();
}
 
int main(void)
{
    Test t(8);
    Cmf(t);
    system("pause");
    return 0;
}

参考文章:
https://www.runoob.com/w3cnote/cpp-const-keyword.html

相关文章

  • C++基础

    const关键字 const关键字标识常量,标明const右侧的变量(本质是常量)不可变。int const *b...

  • Go入门7:常量 const

    const关键字 const variable type = value; 简单定义: const LENGTH ...

  • const/static/extern/const/static

    const -- 常量 const中文意思是“常量”,不可改变的固定的。const关键字主要作用: const ...

  • Item 03:尽可能使用const

    Item 03: Use const whenever possible 关键字const const允许你指定一...

  • const 关键字的学习

    一、const 修饰普通类型的变量 a 被定义为一个常量,并且可以将 a 赋值给 b,但是不能给 a 再次赋值。对...

  • Dart 基本语法

    Final以及Const 在 Dart 中使用 final 以及 const 关键字来申明常量。使用 const ...

  • js 中声明常量关键字 var、let、const

    js 中声明常量的关键字:var、let、const,其中 let 和 const 是 ES6 中新增的关键字。 ...

  • 兼容问题

    六、const 问题firefox / chrome 可以使用const关键字或var关键字来定义常量但是ie下只...

  • 常见浏览器兼容问题

    JS相关 1. const问题 说明:Firefox下,可以使用const关键字或var关键字来定义常量;IE下,...

  • const在C语言上的定义和用法

    我们经常可以在函数接口参数位置看到有const关键字,但是这个关键字到底有什么作用呢?其实const关键字的作用主...

网友评论

      本文标题:const 关键字的学习

      本文链接:https://www.haomeiwen.com/subject/bwlightx.html