简体   繁体   中英

variable declared in member function is same as member variable

wondering whether this gonna work, and how:

class sample
{
 int i;
 int func1()
  {
   int i = 0;
   i++;
   return i;
  }
}

reason I ask is because I have many member functions and bad name conventions.

When you say int i = 0 you're creating a new variable called i that hides the class member. If you want to access the class's i , you can do this->i . But it's usually better not to cause that kind of confusion in the first place.

Inside the body of func1 , you will be referencing the locally declared int i . In order to reference the class member, you need to reference it explicitly by using the this pointer:

this->i

this is a const pointer passed in to all methods in a class to represent the current instance. It is not passed in when you have a static member function of course.

The reason the locally declared int i is being used first is because it is in the same scope as i++ and return i .

Variables inside func1 refer to int i = 0; (nearest i ).

In C++, identical name variables will be used from same/nearset scope first.

It works fine. All uses of the name i inside the function refer to the i declared inside that function. That is, the function will return 1 every time.

What is your intention of i inside the func1(). Do you want to increment the outside i or the i inside the function. If you want the outside i to increment then this won't work.

Things get weird with scopes:

int func1()
{
    int i = 0;
    i++;
    { //1
        int i = 41;
        i++;
    }
    { //2
        int j = i + 1;
        cout << j << endl // this prints 2
    }
    return i;
}

The rule when using variables in scope is, it always refers to the most local scope first and works it way up. So in your example the i inside your function will not refer to the i in the class.

The return will in fact refer to the i declared in func1() . It's all about scopes.

A scope starts with { and end with } . All variables declared inside a scope will only be defined as long you stay within the scope or if you go into another scope. Hence

{ int i = 0; { int i = 1; { int i = 2; }}}

is perfectly possible. If you use i in one of the scopes you will always refer to the i in the same scope. To refer to an i of a higher scope is more difficult.

In your example you can still refer to the top i by using this->i , where this is a pointer to the object you are working with. Here is some more info (scroll a bit down).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM