在下面的程序中,我在func()
中添加了显式的return
语句,但是编译器给出了以下错误:
m.cpp: In function ‘constexpr int func(int)’:
m.cpp:11:1: error: body of constexpr function ‘constexpr int func(int)’ not a return-statement
}
这是代码:
#include <iostream>
using namespace std;
constexpr int func (int x);
constexpr int func (int x)
{
if (x<0)
x = -x;
return x; // An explicit return statement
}
int main()
{
int ret = func(10);
cout<<ret<<endl;
return 0;
}
我已经使用以下命令在 g++ 编译器中编译了程序。
g++ -std=c++11 m.cpp
我在函数中添加了return
语句,然后为什么会出现上述错误?
最佳答案
在 C++14 之前,constexpr
函数的主体必须仅由 return
语句组成:它不能包含任何其他语句。这在 C++11 中有效:
constexpr int func (int x)
{
return x < 0 ? -x : x;
}
在 C++14 及更高版本中,您编写的内容是合法的,就像大多数其他语句一样。
关于c++ - constexpr 函数的主体不是返回语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45097171/