網(wǎng)站首頁 編程語言 正文
C++中constexpr函數(shù)使用
簡介
constexpr函數(shù)指的是在編譯的時(shí)候就能得到其返回值的函數(shù),也就是說編譯器將constexpr函數(shù)直接轉(zhuǎn)換成其返回值,因此,constexpr函數(shù)都是被隱式地定義為內(nèi)聯(lián)函數(shù)。
使用constexpr關(guān)鍵字來修飾constexpr函數(shù)。
使用方法
有如下代碼:
constexpr int myFunc()
{
? return 1;
}
constexpr int i = myFunc() * 4;
此時(shí),編譯器會(huì)將myFunc()函數(shù)用其返回值1來代替,在編譯時(shí)就可知i的值是4。
注意事項(xiàng)
constexpr函數(shù)的返回值類型必須是字面值類型
int g_i = 1;
constexpr int myFunc()
{
? return g_i;
}
此時(shí)的返回值g_i不是字面值類型,因此報(bào)錯(cuò)信息為“error C3256: “g_i”: 變量使用不生成一個(gè)常量表達(dá)式”。
constexpr函數(shù)的形參可以是非常量,但是實(shí)參必須是常量
constexpr int myFunc(int i)
{
? return i;
}
constexpr int i = myFunc(1) * 4;
此時(shí),myFunc()函數(shù)的實(shí)參是常量,在編譯時(shí)可以直接被替換為1,程序不報(bào)錯(cuò)。
int j = 2;
constexpr int i = myFunc(j) * 4;
此時(shí),myFunc()函數(shù)的實(shí)參是非常量,程序報(bào)錯(cuò)信息為“error C2131: 表達(dá)式的計(jì)算結(jié)果不是常數(shù)”,將j定義為const int則不報(bào)錯(cuò)。
函數(shù)體中必須有且只有一條return語句
如下代碼
constexpr int myFunc(int i)
{
? int j;
? return i;
}
程序的報(bào)錯(cuò)信息為“error C3250: “j”: 不允許在“constexpr”函數(shù)體中進(jìn)行聲明”。
C++ constexpr函數(shù)的處理
constexpr函數(shù)是指用于常量表達(dá)式的函數(shù)
需要遵守如下約定:
1) 函數(shù)的返回類型以及所有形參的類型都得是字面值類型,
2) 函數(shù)體中必須有且僅有一條return語句
3) constexpr函數(shù)不一定返回常量表達(dá)式
constexpr int new_sz(); {return 33;}
constexpr int foo_ = new_sz(); //正確,foo_是常量表達(dá)式
原文鏈接:https://blog.csdn.net/hou09tian/article/details/110470363
相關(guān)推薦
- 2022-12-21 Python中Turtle庫改變畫筆(海龜)方向的兩種方法總結(jié)_python
- 2022-04-01 hive not in效率優(yōu)化
- 2022-11-07 將.py文件轉(zhuǎn)化為.exe文件的詳細(xì)過程_python
- 2022-09-24 C語言利用面試真題理解指針的使用_C 語言
- 2023-03-22 Python利用模糊哈希實(shí)現(xiàn)對比文件相似度_python
- 2023-06-04 pandas.DataFrame?Series排序的使用(sort_values,sort_inde
- 2024-07-15 arthas操作spring被代理目標(biāo)對象命令速查
- 2022-04-18 python?selenium在打開的瀏覽器中動(dòng)態(tài)調(diào)整User?Agent_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支