Class method and variable with same name, compile error in C++ not in Java?

前端 未结 6 2111
执念已碎
执念已碎 2020-11-30 05:52
class Test {

      bool isVal() const {
          return isVal;
      }

  private:

      bool isVal;
};

On Compiling this file it says

6条回答
  •  孤独总比滥情好
    2020-11-30 06:19

    C++ applies name mangling to function names and global variables. Local variables are not mangled. The problem arises because in C you can access the address of a variable or a function (thus in C++ as well) e.g. :

    struct noob{
        bool noobvar;
        void noobvar(){};
    };
    

    One can say, why not apply name mangling to local variables as well and then have an internal local representation such as

    bool __noobvar_avar;
    void __noobvar_void_fun;
    

    and suppose that they receive the addresses during execution 0x000A and 0x00C0 respectively.

    However if we write somewhere in the code:

    &noob::noobvar
    

    What should the program do ?

    1. return the address of the variable noobvar , i.e. 0x000A
    2. return the addres of the noobvar function , i.e. 0x00C0

    You can see that since in C , and therefore in C++ , you can issue an "address of", it is not legal to have variables and functions with the same name within the same scope of resolution.

提交回复
热议问题