c++11 常量表达式
生活随笔
收集整理的這篇文章主要介紹了
c++11 常量表达式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
c++11 常量表達(dá)式
?
#define _CRT_SECURE_NO_WARNINGS#include <iostream> #include <string> #include <vector> #include <map>/*** 常量表達(dá)式主要是允許一些計(jì)算發(fā)生在編譯時(shí),即發(fā)生在代碼編譯而不是運(yùn)行的時(shí)候。* 這是很大的優(yōu)化:假如有些事情可以在編譯時(shí)做,它將只做一次,而不是每次程序運(yùn)行時(shí)都計(jì)算。*//* constexpr函數(shù)的限制: 函數(shù)中只能有一個(gè)return語句(有極少特例) 函數(shù)必須返回值(不能是void函數(shù)) 在使用前必須已有定義 return返回語句表達(dá)式中不能使用非常量表達(dá)式的函數(shù)、全局?jǐn)?shù)據(jù),且必須是一個(gè)常量表達(dá)式 */ constexpr int GetConst() {return 3; } //err,函數(shù)中只能有一個(gè)return語句 constexpr int data() {constexpr int i = 1;return i; } constexpr int data2() {//一個(gè)constexpr函數(shù),只允許包含一行可執(zhí)行代碼//但允許包含typedef、 using 指令、靜態(tài)斷言等。static_assert(1, "fail");return 100; }int a = 3; constexpr int data3() {return a;//err, return返回語句表達(dá)式中不能使用非常量表達(dá)式的函數(shù)、全局?jǐn)?shù)據(jù) }/* 常量表達(dá)式的構(gòu)造函數(shù)有以下限制: 函數(shù)體必須為空 初始化列表只能由常量表達(dá)式來賦值 */ struct Date {constexpr Date(int y, int m, int d): year(y), month(m), day(d) {}constexpr int GetYear() { return year; }constexpr int GetMonth() { return month; }constexpr int GetDay() { return day; }private:int year;int month;int day; };void mytest() {int arr[GetConst()] = {0};enum {e1 = GetConst(), e2};constexpr int num = GetConst();constexpr int func(); //函數(shù)聲明,定義放在該函數(shù)后面constexpr int c = func(); //err, 無法通過編譯, 在使用前必須已有定義 constexpr Date PRCfound {1949, 10, 1};constexpr int foundmonth = PRCfound.GetMonth();std::cout << foundmonth << std::endl; // 10return; }constexpr int func() {return 1; }int main() {mytest();system("pause");return 0; }?
總結(jié)
以上是生活随笔為你收集整理的c++11 常量表达式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于移动端meta设置(未完待续)
- 下一篇: Visual C++ 时尚编程百例005