简体   繁体   English

程序的意外 output

[英]unexpected output of a program

I have written a basic program in C++ as below:我在 C++ 中编写了一个基本程序,如下所示:

#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它的 Output 相当惊人 a: 5 b: 4 a: 5 b: 4

Why the value of a and b didn't change.为什么 a 和 b 的值没有改变。 If I replace the set() function as below如果我更换 set() function 如下

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然后 output 符合预期: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 .set function 中, a的所有三个实例都是局部参数变量a ,而不是成员变量a

A variable declared in a narrower scope hides variables of the same name in a wider scope.在较窄的 scope 中声明的变量会在较宽的 scope 中隐藏同名变量。 Here the narrow scope is the function and the wide scope is the object.这里窄 scope 是 function 和宽 scope 是 ZA8CFDE6331BD59EB66AC96F8911C4。

To explicitly use the member variable, you need to say so with this->a :要显式使用成员变量,您需要使用this->a说明:

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

Or或者

this->a += a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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