In C++, what is the scope resolution (“order of precedence”) for shadowed variable names?

后端 未结 2 1098
走了就别回头了
走了就别回头了 2020-12-15 20:39

In C++, what is the scope resolution (\"order of precedence\") for shadowed variable names? I can\'t seem to find a concise answer online.

For example:



        
2条回答
  •  醉梦人生
    2020-12-15 21:23

    It should print out 3. The basic rule is mostly to work your way backward through the file to the most recent definition the compiler would have seen (edit: that hasn't gone out of scope), and that's what it uses. For variables that are local to a class, you follow the same except that all class variables are treated as if they were defined at the beginning of the class definition. Note that this is more or less unique to classes though. For example, given code like:

    int i;
    
    int x() { 
        std::cout << i << '\n'; // prints 0;
        int i=1;
    }
    

    Even though there is an i that's local to the function, the most recent definition seen where cout is used is the global, so that's what the i in that expression refers to. If, however, this were in a class:

    int i;
    
    class X { 
        void y() { std::cout << i << "\n"; }
    
        X() : i(2) {}
    
        int i;
    };
    

    Then the cout expression would refer to X::i even though its definition hasn't been seen yet when y is being parsed.

提交回复
热议问题