2017-09-11 15 views
3

私はC++を新しく導入しました。ローカル変数とグローバル変数を印刷するときにいくつかの問題が発生しています。私の目標は、さまざまなスコープ内の変数のアクセシビリティを実践し、それらを印刷しているC++のグローバル変数とローカル変数

#include <cstdlib> 
#include <iostream> 

using namespace std; 

/* 
* 
*/ 
int x = 10; // This x is global 
int main() { 
    int n; 
    { // The pair of braces introduces a scope 
    int m = 10; // The variable m is only accessible within the scope 
    cout << m << "\n"; 

    int x = 25; // This local variable x hides the global x 
    int y = ::x; // y = 10, ::x refers to the global variable x 
    cout << "Global: " << y << "\n" << "Local: " << x << "\n"; 
    { 
     int z = x; // z = 25; x is taken from the previous scope 
     int x = 28; // it hides local variable x = 25 above 
     int t = ::x; // t = 10, ::x refers to the global variable x 
     cout << "(in scope, before assignment) t = " << t << "\n"; 
     t = x; // t = 38, treated as a local variableout was not declared in this scope 
     cout << "This is another hidden scope! \n"; 
     cout << "z = " << z << "\n"; 
     cout << "x = " << x << "\n"; 
     cout << "(in scope, after re assignment) t = " << t << "\n"; 
    } 
    int z = x; // z = 25, has the same scope as y 
    cout << "Same scope of y. Look at code! z = " << z; 
    } 
    //i = m; // Gives an error, since m is only accessible WITHIN the scope 

    int m = 20; // This is OK, since it defines a NEW VARIABLE m 
    cout << m; 

    return 0; 
} 

:このコードのシンプルな作品を考えてみましょう。しかし、最後の変数zを印刷しようとしたときに、NetBeansが出力2025を返す理由を理解できません。 ここでは私のサンプル出力を次に示します。

10 
Global: 10 
Local: 25 
(in scope, before assignment) t = 10 
This is another hidden scope! 
z = 25 
x = 28 
(in scope, after re assignment) t = 28 
Same scope of y. Look at code! z = 2520 
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms 

は、誰かが何が起こっているか理解する私を助けることができることを願ってい! :)

+4

をそれは20です。 – tkausl

+1

ええ、私はどのように愚かなのですか:(ありがとうたくさんのBTW – KNFZ

答えて

4

あなたは... Zが値を保持していることは、あなたがZを印刷し、メートルを印刷する間の新しいライン演算子を追加するOMMITという事実であることを

ではありません

cout << "Same scope of y. Look at code! z = " << z; 
} 

int m = 20; 
cout << m; 

ができますが、実行する必要があります:やっ

std::cout << "Same scope of y. Look at code! z = " << z << std::endl; 
} 

int m = 20; 
std::cout << m << std::endl; 

あなただけが出力観察することによって、より高速な問題を発見します出力を標識し、

std::cout << "M is: "<<m << std::endl; 

ような何かをすることの同じ基準続く場合:後であなたが `印刷するので

25M is: 20 
関連する問題