小白请问:子类的对象调用基类的共有函数,为什么一直都是初始值

小白请教:子类的对象调用基类的共有函数,为什么一直都是初始值
#include "iostream"
using namespace std;
class Date
{
public:

Date(int y=0,int m=0, int d=0)
{
year=y;
month=m;
day=d;
}
void ddisp() const
{
cout << year << "--" << month << "--" << day;
}
private:
int year, month , day;

};
class Time
{
public:

Time (int h=0, int m=0, int s=0)
{
hour=h;
minute=m;
second=s;
}
void tdisp()
{
cout << hour << ":" << minute << ":" << second << endl;
}
private:
int hour, minute, second;

};
class  DateTime : public Date , public Time
{
};
void main()小白请问:子类的对象调用基类的共有函数,为什么一直都是初始值
{
Date d(2015,9,7);
Time t(17,17,17);

DateTime dt;
dt.ddisp();
cout << endl;
dt.tdisp();

}
------解决思路----------------------
你的
DateTime dt;

和前面定义的变量
Date d(2015,9,7);
Time t(17,17,17);

没有任何关系,而dt使用默认构造函数,输出当然都是默认值
------解决思路----------------------
class  DateTime : public Date , public Time
{
   DateTime(int a,int b,int c):Time(a,b,c),Date(a,b,c){}
};
------解决思路----------------------
你创建的d和t是两个独立的对象,dt是另一个对象,他们在内存中是完全独立的,没有任何关联,所以dt内部的成员变量都是空值。改成如下即可:
#include <iostream>
using namespace std;

class Date
{
public:
    Date(int y = 0, int m = 0, int d = 0)
        :year(y),month(m),day(d){}
    virtual ~Date(){}
    void ddisp()const
    {
        cout << year << "--" << month << "--" << day;
    }
    int getyear(){return year;}
    int getmonth(){return month;}
    int getday(){return day;}
protected:
    int year, month, day;
};

class Time
{
public:
    Time(int h = 0, int m = 0, int s = 0)
        :hour(h),minute(m),second(s){}
    virtual ~Time(){}
    void tdisp()
    {
        cout << hour << "--" << minute << "--" << second <<endl;
    }
    int gethour(){return hour;}
    int getminute(){return minute;}
    int getsecond(){return second;}
protected:
    int hour, minute, second;
};


class DateTime: public Date, public Time
{
public:
    DateTime(){}
    DateTime(Date d, Time t)
    {
        year = d.getyear();
        month = d.getmonth();
        day = d.getday();
        hour = t.gethour();
        minute = t.getminute();
        second = t.getsecond();
    }
    virtual ~DateTime(){}
};

int main()
{
    Date d(2015, 9, 7);
    Time t(17, 17, 17);

    DateTime dt(d, t);
    dt.ddisp();
    cout << endl;
    dt.tdisp();
    return 0;
}