首页 > 解决方案 > C++ 错误:调用非 constexpr 函数

问题描述

我正在尝试编译以下 C++ 代码(另存为 example4.cpp)

#include <iostream>

using namespace std;

constexpr double nth(double x, int n);//initialization

int main()
{
double x=2;
int n=5;
nth(x,n);//Function call
return 0;
}


constexpr double nth(double x, int n)   // function definition
{
    double res = 1;
    int i = 0;
    while (i<n) {   // while-loop: do while the condition is true
         res*=x;
         ++i;
    }
cout << res;
cout << endl;
    return res;
}

此代码给出以下错误:

example4.cpp:在函数 'constexpr double nth(double, int)' 中:example4.cpp:24:9:错误:调用非 constexpr 函数 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream <_CharT, _Traits>::operator<<(double) [with _CharT = char; _Traits = std::char_traits; std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream]' cout << res;

有人可以建议吗?

谢谢你。

标签: c++

解决方案


在函数上下文中std::cout不允许流式传输。事实上,只有有限的一组东西是。阅读关于.constexprconstexpr


推荐阅读