const常量

const applies to the thing left of it. If there is nothing on the left then it applies to the thing right of it.

const默认作用于其左边的东西,否则作用于其右边的东西

const 常量

(const int) max=100;
(int const) max=100;

上面定义,在编译器层面完全等价,普通变量被const修饰后便不可以被修改

const int max=100;
max=50; // 错误,再次赋值便会出现错误

const int *p 与 int const *p

常量指针(表示指针指向的变量是常量)

(const int) *p;
(int const) *p;

指针指向的对象是const,就是指向的变量的值不可变,但指针可以修改指向地址;

#include <stdio.h>

int main(void) {
    int num2=7;
    int num3=8;
    int const *b;
    b=&num3;    // 修改了指针指向地址
    printf("%d\n",*b);

    int num4=9;
    int num5=10;
    const int *c=&num4;
    c=&num5;    // 修改了指针指向地址
    printf("%d\n",*c);

    return 0;
}

int* const p

指针常量(表示指针是常量)

int (*const) p=&b; //指针常量

指针指向的对象可以修改,但指针不可以修改指向地址;

#include <stdio.h>

int main(void) {
    int num1=5;
    int* const a=&num1;
    num1=6;     // 修改了指针指向变量值
    printf("%d\n",*a);

    return 0;
}

常对象:

1.类名 const 对象名(实参列表)
2.Const 类名 对象名 (实参列表)

注意:常对象只能调用const型成员函数(防止非const型的成员函数修改常对象中的数据成员的值)

常成员函数:void print() const;
常数据成员:可以通过参数初始化列表对其赋值

数据成员 非const成员函数 Const数据成员
非const数据成员 可以引用可以改变值 可以引用不可以改变值
常成员函数 const数据成员 可以引用不可以改变值 可以引用不可以改变值
常对象 const对象的数据成员 不可以引用和改变值 可以引用不可以改变值

结尾

优质博客推荐:https://blog.csdn.net/qq_45615577/article/details/121132201

posted @   帅气的涛啊  阅读(454)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示

目录