为什么此测试总是返回false?

0 c++ variables scope if-statement

请忽略此代码的上下文。当时的想法是命名的函数shop()将采取两个参数(money_in_pocketage),并确定这些值将让他们成为劳力士专卖店。但是,即使参数满足if语句中的要求 shop(),程序仍将继续输出“ Leave!”-表示离开存储区。

您可能已经注意到,我是该语言的新手,所以对您的帮助将不胜感激。

我试图使参数远远大于if 语句要求的参数。输出为“ leave!”,因此我尝试了不符合要求的参数,并显示了相同的输出...

#include <iostream>

using namespace std;

class rolex{

   public:
      bool shop(int x, int y){
         if((x >= 5000 && y>= 18)||(x>=5000 && y<18)){
            bool enterence = true;
         }else{
            bool enterence = false;
         };
         return enterence;
      }
   private:
      bool enterence;
};

int main()
{
   rolex objj;

   if( objj.shop(5000, 18) == true){
      cout<<"you may enter"<<endl;
   }else{
      cout<<"LEAVE"<<endl;
   }
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 5

在if语句中

     if((x >= 5000 && y>= 18)||(x>=5000 && y<18)){
        bool enterence = true;
     }else{
        bool enterence = false;
     };
Run Code Online (Sandbox Code Playgroud)

您声明了两个退出if语句后将不活动的局部变量。

因此,数据成员rolex::enterence未初始化且具有不确定的值。

像这样更改if语句

     if((x >= 5000 && y>= 18)||(x>=5000 && y<18)){
        enterence = true;
     }else{
        enterence = false;
     };
Run Code Online (Sandbox Code Playgroud)

考虑到if语句中的条件等于

     if( x >= 5000 ){
Run Code Online (Sandbox Code Playgroud)

您可以只写而不是if语句

enterence = x >= 5000;
Run Code Online (Sandbox Code Playgroud)

要么

rolex::enterence = x >= 5000;
Run Code Online (Sandbox Code Playgroud)