当前位置: 首页 > news >正文

C++ const关键字有多种用法举例

C++ const关键字有多种用法

可以用来修饰变量、指针、函数参数、成员函数等。可以看到const在C++中有多种用法,主要用于保证数据的不可变性,增强代码的安全性和可读性。在实际编程中,根据需要选择适当的const用法,可以有效避免意外修改数据,提高程序的稳定性

以下是一些常见的用法及其示例:

1. 修饰普通变量

const可以用来声明常量,即变量的值在初始化后不能被修改。

#include <iostream>int main() {const int num = 10;// num = 20;  // Error: cannot assign to variable 'num' with const-qualified type 'const int'std::cout << "num: " << num << std::endl;return 0;
}

2. 修饰指针

const修饰指针时有多种情况,取决于const的位置。

2.1 指向常量的指针

指针本身可以改变,但不能通过该指针修改它所指向的值。

#include <iostream>int main() {int value = 10;const int *ptr = &value;// *ptr = 20;  // Error: read-only variable is not assignablevalue = 20;  // Allowed, since value itself is not constptr = nullptr;  // Allowed, ptr itself is not conststd::cout << "value: " << value << std::endl;return 0;
}

2.2 常量指针

指针本身是常量,但可以修改它所指向的值。

#include <iostream>int main() {int value = 10;int *const ptr = &value;*ptr = 20;  // Allowed, can modify the value pointed to// ptr = nullptr;  // Error: cannot assign to variable 'ptr' with const-qualified type 'int *const'std::cout << "value: " << value << std::endl;return 0;
}

2.3 指向常量的常量指针

指针本身和指向的值都不能改变。

#include <iostream>int main() {int value = 10;const int *const ptr = &value;// *ptr = 20;  // Error: read-only variable is not assignable// ptr = nullptr;  // Error: cannot assign to variable 'ptr' with const-qualified type 'const int *const'std::cout << "value: " << value << std::endl;return 0;
}

3. 修饰函数参数

const可以用来修饰函数参数,以保证函数内部不能修改参数的值。

3.1 按值传递的常量参数

这种情况虽然参数在函数内部不能修改,但因为按值传递,函数外部的变量不受影响。

#include <iostream>void printValue(const int value) {// value = 20;  // Error: cannot assign to variable 'value' with const-qualified type 'const int'std::cout << "Value: " << value << std::endl;
}int main() {int num = 10;printValue(num);return 0;
}
3.2 按引用传递的常量参数

这种情况既可以避免不必要的复制,又保证了函数内部不能修改参数的值。

#include <iostream>void printValue(const int &value) {// value = 20;  // Error: cannot assign to variable 'value' with const-qualified type 'const int &'std::cout << "Value: " << value << std::endl;
}int main() {int num = 10;printValue(num);return 0;
}

4. 修饰成员函数

const成员函数表示该函数不会修改对象的状态,不能修改类的成员变量(除非是用mutable关键字修饰的变量)。

#include <iostream>class MyClass {
public:int getValue() const {// value = 20;  // Error: cannot assign to non-static data member within const member functionreturn value;}void setValue(int v) {value = v;}private:int value = 10;
};int main() {MyClass obj;std::cout << "Value: " << obj.getValue() << std::endl;obj.setValue(20);std::cout << "Value: " << obj.getValue() << std::endl;return 0;
}

5. 顶层const和底层const

顶层const(Top-level const):指对象本身是常量,例如 const int a = 10;。
底层const(Low-level const):指对象的内容是常量,例如 const int *ptr;。

6. 修饰返回类型

const可以修饰返回类型,防止返回值被修改。

#include <iostream>class MyClass {
public:const int& getValue() const {return value;}private:int value = 10;
};int main() {MyClass obj;const int& val = obj.getValue();// val = 20;  // Error: cannot assign to variable 'val' with const-qualified type 'const int &'std::cout << "Value: " << val << std::endl;return 0;
}

7. 修饰常量表达式

constexpr是C++11引入的,用于声明常量表达式,保证表达式在编译时计算。

#include <iostream>constexpr int square(int x) {return x * x;
}int main() {const int result = square(5);std::cout << "Result: " << result << std::endl;return 0;
}
http://www.lryc.cn/news/372795.html

相关文章:

  • Makefile-快速掌握
  • 定个小目标之刷LeetCode热题(20)
  • 短剧分销小程序:影视产业链中的新兴力量
  • 使用fvm切换flutter版本
  • python通过selenium实现自动登录及轻松过滑块验证、点选验证码(2024-06-14)
  • 【C++】开源项目收集
  • 爬虫相关面试题
  • Spring Cloud Netflix 之 Ribbon
  • C语言怎样记住那么多的颜⾊?
  • LabVIEW软件开发任务的工作量估算方法
  • 【已解决】引入 element 组件无法使用编译错误 ERROR Failed to compile with 1 error
  • Prometheus的四种指标类型
  • FastDFS SpringBoot 客户端 Demo搭建,支持文件上传下载
  • 十大成长型思维:定位思维、商业思维、时间管理思维、学习成长思维、精力管理思维、逻辑表达思维、聚焦思维、金字塔原理、目标思维、反思思维
  • GraphQL(9):Spring Boot集成Graphql简单实例
  • vue3+ Element-Plus 点击勾选框往input中动态添加多个tag
  • 唯美仙侠手游【九幽仙域】win服务端+GM后台+详细教程
  • Qt creator day2练习
  • 哪里有海量的短视频素材,以及短视频制作教程?
  • 文章MSM_metagenomics(三):Alpha多样性分析
  • Web前端与其他前端:深度对比与差异性剖析
  • AI 客服定制:LangChain集成订单能力
  • 【计算机毕业设计】242基于微信小程序的外卖点餐系统
  • java程序监控linux服务器硬件,cpu、mem、disk等
  • 高考报志愿闲谈
  • 面试官考我Object类中的所有方法及场景使用?我...
  • Web前端精通教程:深入探索与实战指南
  • 四轴飞行器、无人机(STM32、NRF24L01)
  • OpenAI Assistants API:如何使用代码或无需代码创建您自己的AI助手
  • CentOS7 配置Nginx域名HTTPS