程序的意外输出

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

它的输出相当惊人 a: 5 b: 4 a: 5 b: 4

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

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

然后输出如预期: a: 5 b: 4 a: 6 b: 10

回答

当你做

a = a + a;

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

在较窄范围内声明的变量会在较宽范围内隐藏同名变量。这里窄范围是函数,宽范围是对象。

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

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

或者

this->a += a;

  • May I suggest adding a little to say `asd(int a, int b): a(a),b(b){}` is a special case where `a(a)` has an implied `this->a(a)`.

以上是程序的意外输出的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>