14

const オブジェクトである int へのポインターを使用して constexpr 宣言を初期化しようとしています。また、const 型ではないオブジェクトを使用してオブジェクトを定義しようとしています。

コード:

#include <iostream>

int main()
{
constexpr int *np = nullptr; // np is a constant to int that points to null;
int j = 0;
constexpr int i = 42; // type of i is const int
constexpr const int *p = &i; // p is a constant pointer to the const int i;
constexpr int *p1 = &j; // p1 is a constant pointer to the int j; 
}

g++ ログ:

constexpr.cc:8:27: error: ‘&amp; i’ is not a constant expression
constexpr.cc:9:22: error: ‘&amp; j’ is not a constant expression

メインのオブジェクトに固定アドレスがないためだと思います。したがって、g ++ がエラーメッセージを返してくれます。これをどのように修正しますか?リテラル型を使用しない。

4

1 に答える 1

21

アドレスstaticを修正するようにします。

int main()
{
  constexpr int *np = nullptr; // np is a constant to int that points to null;
  static int j = 0;
  static constexpr int i = 42; // type of i is const int
  constexpr const int *p = &i; // p is a constant pointer to the const int i;
  constexpr int *p1 = &j; // p1 is a constant pointer to the int j; 
}

これは、アドレス定数式[5.19p3]として知られています。

アドレス定数式は、静的記憶域期間を持つオブジェクトのアドレス、関数のアドレス、null ポインター値、または std 型の prvalue コア定数式に評価されるポインター型の prvalue コア定数式です。 :nullptr_t.

于 2012-11-21T21:50:36.317 に答える