冲突名称的成员变量和方法变量 temp 很多C++程序员都会为所有类数据成员遵守常规的前缀 My。 < P>最内层 TEMP将默认使用。

冲突名称的成员变量和方法变量 temp 很多C++程序员都会为所有类数据成员遵守常规的前缀 My。 < P>最内层 TEMP将默认使用。,c++,oop,C++,Oop,下面是它的工作原理: struct Foo { double temp; void bar() { double temp; // "hides" the member temp = 3.0; // assigns to the local this->temp = 5.0; // assigns to the member } void baz() { temp = 3.0

下面是它的工作原理:

struct Foo
{
   double temp;

   void bar()
   {
      double temp;       // "hides" the member
      temp = 3.0;        // assigns to the local
      this->temp = 5.0;  // assigns to the member
   }

   void baz()
   {
      temp = 3.0;        // assigns to the member
      this->temp = 5.0;  // assigns to the member
   }
};
.

以下是它的工作原理:

struct Foo
{
   double temp;

   void bar()
   {
      double temp;       // "hides" the member
      temp = 3.0;        // assigns to the local
      this->temp = 5.0;  // assigns to the member
   }

   void baz()
   {
      temp = 3.0;        // assigns to the member
      this->temp = 5.0;  // assigns to the member
   }
};

.

在较窄范围内定义的变量会隐藏在它们上面定义的变量。某些编译器确实会对此发出警告(您是否使用
-Wall
?)在较窄范围内定义的变量将其上面定义的变量隐藏起来。某些编译器确实会对此发出警告(您是使用
-Wall
编译的吗?)

默认情况下将使用最里面的
temp

如果要访问类成员,请使用
this->temp


很多C++程序员都会为所有类数据成员遵守常规的前缀 My

< P>最内层<代码> TEMP将默认使用。

如果要访问类成员,请使用
this->temp


< >许多C++程序员都为所有类数据成员遵守常规的前缀<代码> My<代码>。< > P> <强>范围规则< /强>命令编译器如何查找变量名。< /P> 在您的情况下,本地
temp
隐藏了成员变量
temp
,因此对
temp
的所有引用都将解析为本地
temp

要解决此问题,请使用
this
指针显式获取成员变量:

this->temp = .... // member variable
temp = .... // local variable

范围规则规定编译器将如何查找变量名

在您的情况下,本地
temp
隐藏了成员变量
temp
,因此对
temp
的所有引用都将解析为本地
temp

要解决此问题,请使用
this
指针显式获取成员变量:

this->temp = .... // member variable
temp = .... // local variable

@约翰迪林:我们不需要代码。这不是一个一般性的问题。依我看,这个问题是合理的。@Sean:那差不多是4年前的事了。当时这里的情况大不相同。无论如何,我已经重新阅读了这个问题,并决定我在这里跳枪。c/v已还原。@约翰迪林:我们不需要代码。这不是一个一般性的问题。依我看,这个问题是合理的。@Sean:那差不多是4年前的事了。当时这里的情况大不相同。无论如何,我已经重新阅读了这个问题,并决定我在这里跳枪。c/v恢复了。@LightnessRacesinOrbit:如果我们的公司合并,我可能会觉得有点不安;-)我不会与那些自1750年代后期以来一直坚持匈牙利语符号的公司合并:)@LightnessRacesinOrbit:如果我们的公司合并,我可能会感到有点不安;-)我不会与那些从1750年代后期开始继续坚持匈牙利ish符号的公司合并:)
-Wall
不包括
-Wshadow
-Wall
不包括
-Wshadow