簡體   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