繁体   English   中英

程序的意外 output

[英]unexpected output of a program

我在 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;
}

它的 Output 相当惊人 a: 5 b: 4 a: 5 b: 4

为什么 a 和 b 的值没有改变。 如果我更换 set() function 如下

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

然后 output 符合预期:a:5 b:4 a:6 b:10

当你这样做

a = a + a;

set function 中, a的所有三个实例都是局部参数变量a ,而不是成员变量a

在较窄的 scope 中声明的变量会在较宽的 scope 中隐藏同名变量。 这里窄 scope 是 function 和宽 scope 是 ZA8CFDE6331BD59EB66AC96F8911C4。

要显式使用成员变量,您需要使用this->a说明:

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

或者

this->a += a;

暂无
暂无

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

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