c++ - 派生类中使用的基本构造函数有问题

标签 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;
}

最佳答案

函数

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();
}

您需要类似地更新显示。使用:

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

关于c++ - 派生类中使用的基本构造函数有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43455931/

相关文章:

c++ - 简单的方法将字符串转换为 int?

c++ - 为什么 std::strong_ordering 有 `equivalent` 值?

c++ - Clang、LLVM 和 g++

c++ - 什么可能导致两个相同的后续 SetWindowPos() 调用设置不同的窗口大小?

c++ - 项目无法与 libcurl 静态库链接

C++实时策略模式处理不同数据

c++ - 找到关联的dll文件到__declspec(dllexport)

按下子按钮时 C++ 窗口失去焦点

php - 从 PHP Web 应用程序调用 C++ 库 : system() vs SWIG PHP extension?

c++ - x64 汇编、ret 寄存器和变量