2012-12-13 8 views
6

非常に簡単な質問。これは有効なC++ 11ですか?別の非staticの非スタティックメンバーイニシャライザ

struct Foo { 
    int bar = 1; 
    int baz = bar; 
}; 

GCC(4.7.2)とクラン(3.1)知識をひけらかすの設定で、それを受け入れる両方:

-std=c++11 -Wall -W -pedantic

インテルC++(13.0.1.117)がありません。

権利である
error: a nonstatic member reference must be relative to a specific object

:それはでint baz = bar;で吠えますか?

あなたが疑問に思う場合

、私はそれがかなりコンストラクタに最後の行を移動するよりも、より緊密初期化コードをもたらし、このようなコード、のためにこれを使用します。

uint8_t colorR = -1; 
uint8_t colorG = -1; 
uint8_t colorB = -1; 
uint8_t colorA = -1; 
GLubyte RGBAVec[4] = {colorR, colorG, colorB, colorA}; 

答えて

3

5.1p12 An id-expression that denotes a non-static data member or non-static member function of a class can only be used:

  • as part of a class member access (5.2.5) in which the object expression refers to the member’s class or a class derived from that class, or
  • to form a pointer to member (5.3.1), or
  • in a mem-initializer for a constructor for that class or for a class derived from that class (12.6.2), or
  • in a brace-or-equal-initializer for a non-static data member of that class or of a class derived from that class (12.6.2), or
  • if that id-expression denotes a non-static data member and it appears in an unevaluated operand.

そうです、この:

struct Foo { 
    int bar = 1; 
    int baz = bar; 
}; 

は有効なC++ 11です。

しかしので、順序について気をつけ可能:Non-static data member initializers proposal(問題3)で指定されたように

12.6.2p10 In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
  • Finally, the compound-statement of the constructor body is executed

A third issue is that class-scope lookup could turn a compile-time error into a run-time error:

struct S { 
    int i = j; // ill-formed without forward lookup, undefined behavior with 
    int j = 3; 
}; 

(Unless caught by the compiler, i might be intialized with the undefined value of j.)

+0

感謝。それは決定的に見える。 「またはそのクラスから派生したクラス」は何を意味していますか?どのように派生クラスのメンバでメンバを初期化することが可能ですか?派生クラスはまだ宣言されていないため、アクセスすることはできません。 –

+0

@Nikos C. "またはそのクラスから派生したクラスの"は、初期化子が犠牲クラスにあるものであることを意味する "ブレースまたは同等イニシャライザ"を参照します。基本的には、あなたは親クラスの非静的データメンバーで非静的データメンバーを初期化できることを意味すると思います。それはあなたがそれを理解した人の周りのもう一つの方法であり、はるかに意味があります:) – Drax

関連する問題