简体   繁体   中英

unexpected output of a program

I have written a basic program in C++ as below:

#include <iostream>
using namespace std;

class asd {
  int a,b;
  public:

  asd(int a, int b): a(a),b(b){}

  void set(int a, int b) {
    a = a + a;
    b = b + b;
  } 

  void show() {
    cout<<"a: "<<a<<" b :"<<b<<"\n";
  }
};

int main() {
  asd v(5,4);
  v.show();
  v.set(1,6);
  v.show();
   
  return 0;
}

Its Output is quite surprising a: 5 b: 4 a: 5 b: 4

Why the value of a and b didn't change. If I replace the set() function as below

void set(int x, int y) {
  a = a + x;
  b = b + y;
}

then the output is as expected: a: 5 b: 4 a: 6 b: 10

When you do

a = a + a;

in the set function, all three instances of a is the local argument varible a , and not the member variable a .

A variable declared in a narrower scope hides variables of the same name in a wider scope. Here the narrow scope is the function and the wide scope is the object.

To explicitly use the member variable, you need to say so with this->a :

this->a = this->a + a;

Or

this->a += a;

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