2016-07-15 14 views
2

良いスタイルよりも議論がありません。標準的なC++では正当なものに興味があります。これははるかに大きなコードで出てきた小さな例です。メンバ変数の型名と同じ名前を持つことは合法ですか?

ClangとVisual Studioはこれをエラーなくコンパイルし、完全にうまく動作しているようです。私はどちらからも警告をもらえません。

GCCは次のエラーを与え、さらには、コードをコンパイルすることを拒否...

test.cpp:1:8: error: changes meaning of 'test' from 'struct test' [-fpermissive]

は、この法律上のコードであり、そうでありませんか? 私はgccが何を言っているのか理解していますが、このコードは実際には間違っていますか?

struct test 
{ 
    int data; 
}; 


struct app 
{ 
    test test; 
}; 

int main() 
{ 
    app myapp; 
    myapp.test.data = 123; 
} 
+0

データメンバーと変数だけに違いはありません。 –

+0

@ Cheersandhth.-Alf:もちろんあります。 –

+0

@LightnessRacesinOrbit:いいえ。 –

答えて

0

It's invalid、変数とタイプが異なるスコープにあるため。

Hiding kicks in only when they're in the same scope

[C++14: 3.3.10/2]: A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.

クランとVisual Studioが間違っています。

+0

** - 1 **引用した段落はまったく別のもの、つまり名前が共存していることです。 Cの種類の名前空間で、 'struct'キーワードを使って解決しました。 –

+0

@ Cheersandhth.-Alf:何ですか?答えを読んだことさえありましたか?この段落では、名前が共存するときに隠すことのみが文字通りのポイントとなります。 –

+0

(私は、OPのケースではそれを許可するルールがないことを証明するために標準の残りの部分を引用することができますが、SOの回答には最大サイズ制限があります) –

関連する問題