对派生类

时间:2017-04-17 17:03:26

标签: c++

我正在运行一个代码,其中我使用两个基类并从中派生派生类。我在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;
}

1 个答案:

答案 0 :(得分: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();
}