我完全是 c++ 的新手,我发现了一些我不明白的东西,我找不到答案(而且我确信它已经被问了很多,所以给我指一个线程也很好).
示例代码:
#include <iostream>
class Car {
int doors;
public:
void set_doors(int doors){
doors = doors;
}
int get_doors(){
return doors;
}
};
int main()
{
Car ford;
ford.set_doors(3);
std::cout << ford.get_doors() << std::endl;
}
所以当我运行代码时,它总是返回一个长度为 9 的 int。
我知道问题正在发生,因为在
void set_doors(int doors)
我对要更改的参数和变量使用相同的名称。 如果我将代码更改为
void set_doors(int newdoors){
doors = newdoors;
}
一切都会完美运行。
我的问题是: 当使用我想修改的变量的名称和参数名称时,为什么代码会这样? 请用简单的方式解释它;)
谢谢
最佳
最佳答案
Why does the code behave like this, when using the name for the variable which I like to modify and the argument name?
因为 C++ 的规则要求它以这种方式运行:局部变量和参数的名称“胜过”成员变量。您应该会收到有关此赋值的编译器警告,说明该赋值无效(它将参数的值赋回给自身)。
解决此问题的惯用方法之一如下:
this->doors = doors;
当一个非限定名称可能指代多个事物时,这就是该语言让您解决情况的方式。
关于当参数名和变量名相等时,c++类 setter 设置不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792970/