当方法参数具有相同的名称时,我们如何引用字段?

How do we refer to a field when method argument has same name?

#include<iostream>
#include<fstream>
using namespace std;

class Integer {
public:
    int val;
    Integer(int val = 0) {
        this->val = val;
    }
    void setVal(int val) {
        this->val = val;
    }
};

int main()
{
    int val;
    Integer i;
    i.setVal(8);
    cout << val << endl;
}

当我执行我的代码时,我得到 0。我是 ​​C++ 的新手,我不明白 this。有人可以详细说明这个问题吗?

您输出错误 val。正如所写,您可以调用 i.val,因为您创建了数据成员 val public,但您也可以选择创建一个函数("getter") 表示整数 class。无论如何,我建议您了解 private 数据成员以及如何使用它们。

getter 方法类似于

// in the class
int getVal() {
  return val; // equal to return this->val
}

// in main()
cout << i.getVal() << endl;

请注意,如果您更改主要功能,您将不再使用 main() 中之前的 val。这也是重点 - 您现在正在使用 class 数据成员!

如需讨论如何绕过使用 this 指针的问题,请查看以下问题:Is using underscore suffix for members beneficial?

此时您似乎也不需要包含 fstream

您发明了 main 中的 val 和对象 i 中的 val 之间的关系。

除了共享一个名字,他们没有任何关系。

  • 删除 main 中未设置的 val
  • 改为输出i.val