Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;11-Can';是否使用constexpr函数定义constexpr文本?_C++_C++11_Gcc_Constexpr - Fatal编程技术网

C++ C++;11-Can';是否使用constexpr函数定义constexpr文本?

C++ C++;11-Can';是否使用constexpr函数定义constexpr文本?,c++,c++11,gcc,constexpr,C++,C++11,Gcc,Constexpr,我遇到了一个似乎违反直觉的错误,即无法将constexpr函数的值分配给constexpr文本(希望我使用的语言是正确的)。下面是一个例子: class MyClass { public: static constexpr int FooValue(int n) { return n + 5; } static constexpr int Foo5 = FooValue(5); // compiler error static constexpr int Foo5Alt(void

我遇到了一个似乎违反直觉的错误,即无法将
constexpr
函数的值分配给
constexpr
文本(希望我使用的语言是正确的)。下面是一个例子:

class MyClass {
 public:
  static constexpr int FooValue(int n) { return n + 5; }
  static constexpr int Foo5 = FooValue(5);  // compiler error
  static constexpr int Foo5Alt(void) { return FooValue(5); }  // OK
};
在GCC 4.8.4中,
Foo5
标记为
字段初始值设定项不是常量。发现表明GCC的旧版本可能是罪魁祸首。因此,我将其插入(GCC 6.2.0)并在其定义完成之前在常量表达式中调用了错误“static constexpr int MyClass::FooValue(int)”。我添加了
Foo5Alt()

我想我不明白为什么
FooValue(5)
不能用作
Foo5
的初始值设定项。
FooValue(intn)
的定义是完整的,不是吗
{return n+5;}
是整个定义
constexpr
表示可以在编译时完全计算的表达式,那么为什么不能使用它来定义
constexpr
文本的返回值呢


<>我缺少什么C++的精妙?<在C++中,类的成员函数内联定义只在类完成声明后被解析。

因此,即使编译器“知道”关于
MyClass::FooValue(int)
,它还没有“看到”它的定义,因此它不能在
constepr
表达式中使用


一个一般的解决办法是坚持<代码> CONTXPRP< /COD>成员函数,或者在类外声明“代码> CONTXPRP</CUD>常量。C++中的

< P>,一个类的成员函数的内联定义只在类完成后被解析。

因此,即使编译器“知道”关于
MyClass::FooValue(int)
,它还没有“看到”它的定义,因此它不能在
constepr
表达式中使用


一般的解决方法是坚持使用
constepr
成员函数,或者在类外声明
constepr
常量。

根据标准,当您试图调用
FooValue
初始化
Foo5
时,
MyClass
被认为是不完整的类型。因此,您不能像以前那样使用其成员。
在结束时,该类型被视为完全定义的对象类型(或完整类型)

另一方面,类在函数体中被认为是完整的。这就是为什么
Foo5Alt
编译得很好。

有关更多详细信息,请参阅。

根据标准,当您尝试调用
FooValue
初始化
Foo5
时,
MyClass
被视为不完整类型。因此,您不能像以前那样使用其成员。
在结束时,该类型被视为完全定义的对象类型(或完整类型)

另一方面,类在函数体中被认为是完整的。这就是为什么
Foo5Alt
编译得很好。
有关更多详细信息,请参阅