多个类,输出

时间:2015-11-29 19:42:11

标签: c++ c++11

我在一个时间点上了一个日期和课程的课程。现在我想把它们结合起来。我的问题是我无法使输出工作,它总是使用初始化日期。 这是我的代码:

的main.cpp

#include <iostream>
#include <iomanip>

#include "date.hpp"
#include "time.hpp"

using namespace std;

int main() {
Datum d1;
Datum d2(03, 12, 2015);

cout << "d1: " << d1 << endl;
cout << "d2: " << d2 << endl << endl;

zeit z1;
cout << "z1: " << z1 << endl;
zeit z2(d2, 23, 30);
cout << "z2: " << z2 << endl;
return 0;
}

date.cpp

#include "date.hpp"
#include <iostream>

Datum::Datum(unsigned int d, unsigned int m, unsigned int y)
{
    day = d;
    month = m;
    year = y;
    return;
}
Datum::Datum() : Datum(1, 1, 2000) { return; }
unsigned int Datum::getday() { return day; }
unsigned int Datum::getmonth() { return month; }
unsigned int Datum::getyear() { return year; }

std::ostream& operator<<(std::ostream& os, Datum& z)
{
    os << z.getday() << ".";
    os << z.getmonth() << ".";
    os << z.getyear();
    return os;
}

date.hpp

#ifndef DATUM_HPP_
#define DATUM_HPP_
#include <iostream>

class Datum {
private:
    unsigned int day;
    unsigned int month;
    unsigned int year;
public:
    Datum(unsigned int, unsigned int, unsigned int);
    Datum();
    unsigned int getday();
    unsigned int getmonth();
    unsigned int getyear();

    friend std::ostream& operator<<(std::ostream&, Datum&);
};
#endif

time.cpp

#include "time.hpp"
#include <iostream>

zeit::zeit(Datum date, unsigned int h, unsigned int m)
{
    std::cout << date.getday() << "." << date.getmonth() << "." <<  date.getyear() << std::endl;
    min = m;
    hour = h;
    return;
}
zeit::zeit() : zeit(Datum(),0,0) { return; }
unsigned int zeit::getmin() { return min; }
unsigned int zeit::gethour() { return hour; }

std::ostream& operator<<(std::ostream& os, zeit& z)
{
    os << z.date << ", ";
    if (z.gethour() < 10)
        os << "0" << z.gethour();
    else
        os << z.gethour();
    os << ":";
    if (z.getmin() < 10)
        os << "0" << z.getmin();
    else
        os << z.getmin();
    return os;
}

time.hpp

#ifndef ZEIT_HPP_
#define ZEIT_HPP_
#include "date.hpp"

class zeit {
private:
    unsigned int min;
    unsigned int hour;
    Datum date;
public:
    zeit(Datum, unsigned int, unsigned int);
    zeit();
    unsigned int getmin();
    unsigned int gethour();

    friend class Datum;
    friend std::ostream& operator<<(std::ostream&, zeit&);
};
#endif

这是我得到的输出:

d1:1.1.2000
d2:3.12.2015

2000年1月1日
z1:1.1.2000,00:00 2015年12月3日
z2:1.1.2000,23:30

我做错了什么? Ty有任何帮助!

1 个答案:

答案 0 :(得分:0)

您没有设置kCLErrorDenied类的内部日期,因此当zeit运算符调用它时,它仍会使用默认日期进行初始化。将此行添加到<<中的zeit的构造函数:

time.cpp