1 Star 0 Fork 2

movetoyushuiqiang / C++11实用新特性

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
常量表达式函数.cpp 1.36 KB
一键复制 编辑 原始数据 按行查看 历史
夜空中最亮的星 提交于 2022-02-08 06:58 . C++11常量表达式函数
#include <iostream>
using namespace std;
#include <string>
//constexpr void func1() // error 不是常量表达式函数 该函数没有返回值
//{
// int a = 100;
// cout << a << endl;
//}
//constexpr int func2() // error 不是常量表达式函数 该函数返回值不是常量表达式
//{
// int a = 100;
// cout << a << endl;
// return a;
//}
class test
{
public:
constexpr test():a(10000)
{
}
constexpr int fun()
{
constexpr int var = 100;
return 5 * var;
}
int a;
};
struct person
{
const char* name;
int age;
};
constexpr int func3();
constexpr int func4() // ok
{
using mytype = int;
constexpr mytype a = 100;
constexpr mytype b = 500;
constexpr mytype c = a * b + 1;
return c;
}
int main()
{
cout << func4() << endl;
//为了提高C++程序的执行效率,我们可以将程序中不会发生变化的值定义为常量,也可以使用comstexpr修饰函数的返回值,这种函数叫常量表达式函数
//constexpr int num = func3;//error 在函数使用之前,必须有对应的定义语句
test t;
constexpr int ret = t.fun();
cout << ret << endl;
cout << t.a << endl;
//常量表达式函数的注意事项:1、函数必须有返回值,函数的返回值必须为常量表达式
//2、函数在使用之前必须有对应的定义语句
//3、整个函数体中,不能出现非常量表达式之外的语句(using指令,typedef语句以及static-assert断言,return语句除外)
return 0;
}
constexpr int func3()
{
constexpr int a = 100;
return a;
}
C++
1
https://gitee.com/jackysq/C--11.git
git@gitee.com:jackysq/C--11.git
jackysq
C--11
C++11实用新特性
master

搜索帮助