2014-10-05 37 views
0

所以我有這個基類。C++ - (If語句)否則總是顯示

class Info{ 
private: 
    string name, sex; 
    int year, month, day, age; 

public: 

    void setInfo(){ 

    string n, s; 

     cout<<"Enter your full name: "; 
     cin>>n; 
     cout<<"Gender: "; 
     cin>>s; 

     name=n; 
     sex=s; 

     cout<<endl; 
    } 

    void setBirthdate(){ 

     int y, m, d, a; 

     cout<<"Birthdate in numerical type"<<endl; 
     cout<<"Year: "; 
     cin>>y; 
     cout<<"Month: "; 
     cin>>m; 
     cout<<"Day: "; 
     cin>>d; 

     a=2014-y; 

     year=y; 
     month=m; 
     day=d; 
     age=a; 

     cout<<endl; 
    } 

    int getYear(){ 
     return year;   
    } 

    int getMon(){ 
     return month; 
    } 

    int getDay(){ 
     return day; 
    } 

    int getAge(){ 
     return age; 
    } 

}; 

而派生類

class Fortunes:public Info{ 

private: 
    string zodiacs; 

public: 

Info fo1; 

    string getZodiac(){ 

     if((fo1.getMon()<=4) && (fo1.getMon()>=3)) 
     { 
     cout<<"Aries"; 
     } 

     else 
      cout<<"aww"; 

    } 




}; 

主類

int main(){ 
Fortunes f; 

f.setInfo(); 
f.setBirthdate(); 
f.getZodiac(); 

cout<<endl; 

system("pause>nul"); 
} 

我想作一個計劃,告訴你的星座基地從您輸入的信息。 所以我只測試了這個小代碼,其他的東西總是顯示出來。 我猜我的操作員是錯的?請幫助我:(

+0

的if語句在我的派生class.The別人總是被顯示 – AhriOmg 2014-10-05 06:57:35

+0

還是一樣壽 – AhriOmg 2014-10-05 07:04:10

+0

不知道你的測試值,我們不能告訴但這看起來很奇怪:'如果(( fo1.getMon()<= 4)&&(fo1.getMon()> = 3))'因爲它只適用於3個月或4個月。 – 2014-10-05 09:12:42

回答

1

您有兩個Info對象創建的實例,一個作爲f的子對象(聲明爲Fortunes f;),另一個聲明爲Info fo1;在Fortune對象內,但fo1未初始化。如下:

class Fortunes:public Info{ 
    public: 
     string getZodiac(){ 

      if((this->getMon()<=4) && (this->getMon()>=3)) 
      { 
      cout<<"Aries"; 
      } 

      else 
       cout<<"aww"; 

     } 

}; 
+0

@polarysekt非常感謝,這是一個錯別字 – 2014-10-05 07:02:50

+0

嘿,我刪除評論你的編輯,總是比較容易反駁ct'別人的回答'。 (如果只有我可以在我自己的代碼中檢測到這樣的事情......)。 – polarysekt 2014-10-05 07:04:34

+0

不知道「這個」,我的教授沒有教我們「這個」 它幫助了謝謝,所以我將在每個使用的生肖上使用「this」。 順便說一句,是他們的任何替代方式,而不是使用它? – AhriOmg 2014-10-05 07:07:40