2017-04-17 28 views
1

我跑在我使用的是兩個基類和它們派生派生類中的代碼中使用。我在Derived類中調用它們的構造函數,並且給出main的參數。當我編譯它時不會給我任何錯誤。但是當我嘗試運行該程序時,程序無法運行,我非常困惑! 這裏是我的代碼含底座的構造有問題,在派生類

#include <iostream> 
#include<iomanip> 
using namespace std; 
class Date 
{ 
     int day; 
     int month; 
     int year; 
public: 

     Date(int d,int m,int y) 
     { 
     day=d; 
     month=m; 
     year=y; 
     } 

     void display() 
     { 
      cout<<endl<<day<<"\\"<<month<<"\\"<<year<<endl; 
     } 
     void set() 
     { 
      cout<<"Enter day :"; 
      cin>>day; 
      cout<<"Enter month :"; 
      cin>>month; 
      cout<<"Enter year :"; 
      cin>>year; 
     } 
       // sets the date members 
    }; 

class Time 
{ 
     int hour; 
     int minute; 
     int second; 
public: 

     Time(int h,int min,int s) 
     { 
      hour=h; 
      minute=min; 
      second=s; 
     } 


     void display() // displays the time 
     { 
      cout<<endl<<hour<<":"<<minute<<":"<<second<<endl; 
     } 
     void set() 
     { 
      cout<<"Enter hour :"; 
      cin>>hour; 
      cout<<"Enter minute :"; 
      cin>>minute; 
      cout<<"Enter seconds :"; 
      cin>>second; 
     } 
       // sets the time members 
    }; 

class DateAndTime : public Date, public Time 
{ 
     int digital; 
public: 

    DateAndTime(int a,int b,int c,int d,int e,int f): 
    Date(a,b,c),Time(d,e,f) 
    { 
    } 


    void set() 
    { 
     Date:set(); 
     Time:set(); 
    } 
    void display() 
     { 
     Date:display(); 
     Time:display(); 
     } 
      // prints date and time 
    }; 
int main() 
{ 
    DateAndTime Watch(17,02,1999,03,36,56); 
    Watch.display(); 
    Watch.set(); 
    Watch.display(); 
    return 0; 
} 
+2

請張貼實際的錯誤是什麼。 – AndyG

+3

您的意思是寫'時間::設置();'你正在使用一個冒號時,你應該使用兩個所有的地方。 – AndyG

+0

我很難相信這個編譯沒有錯誤。你如何編譯?你能提供命令行和任何輸出嗎? 也許添加一些挑剔的交換機像'-Wall'。你能用相同的方法編譯一個小程序嗎?例如。一個典型的「Hello World」。 – Yunnosch

回答

4

功能

void set() 
{ 
    Date:set(); 
    Time:set(); 
} 

錯誤而編譯器不會抱怨,因爲它把Date:Time:的標籤。如果分開標籤和函數調用,功能是:

void set() 
{ 
    Date: // Unused label. 
     set(); // Calls the function again, leading to infinite recursion 
       // and stack overflow. 
    Time: // Unused label. 
     set(); // The function never gets here. 
} 

您需要使用:

void set() 
{ 
    Date::set(); 
    Time::set(); 
} 

你需要同樣更新display。用途:

void display() 
{ 
    Date::display(); 
    Time::display(); 
} 
+0

非常感謝你的幫助這是工作! – Zaina

+0

@Zaina,不客氣。 –

+0

@Zaina請,如果這個答案滿足您的需求,考慮接受的答案。 –