为什么我没有使用我的类的toString方法获取输出?

时间:2018-02-10 15:45:29

标签: c++

Date.h

#include <string>

#ifndef DATE_H_
#define DATE_H_

class Date
{
public:
    static const unsigned int monthsPerYear{12};
    explicit Date(unsigned int d = 1, unsigned int m = 1, unsigned int y = 1900);
    std::string toString() const;
private:
    unsigned int day;
    unsigned int month;
    unsigned int year;
    unsigned int checkDay(unsigned int ) const;
};


#endif /* DATE_H_ */

Date.cpp

#include <iostream>
#include <sstream>
#include <stdexcept>
#include <array>
#include "Date.h"

using namespace std;

Date::Date(unsigned int d, unsigned int m, unsigned int y) : day{checkDay(d)}, month{m}, year{y} {
    if ( month < 1 || month > monthsPerYear ) {
        throw invalid_argument("wrong entry for month");
    }
}

string Date :: toString() const {
    ostringstream output;
    output << day << ":" << month << "/" << year;
    return output.str();
}

unsigned int Date :: checkDay(unsigned int testDay) const {
    static const array<unsigned, monthsPerYear + 1> daysPerMonth{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (testDay <= daysPerMonth[month] && testDay > 0) {
        return testDay;
    }
    return testDay;
}

的main.cpp

#include <iostream>
#include "Date.h"

using namespace std;

int main()
{
    Date d2;
    cout << d2.toString() << endl;
    return 0;
}

我在输出控制台中什么都没有。

2 个答案:

答案 0 :(得分:3)

除了一些程序员老兄确定的UB以及I do get output(将您的代码段转换为单个文件的测试用例后)之外,我看不出有什么问题。

您可以通过checkDay每天月来修复UB:

unsigned int checkDay(unsigned int, unsigned int) const;

Date::Date(unsigned int d, unsigned int m, unsigned int y) : day{checkDay(d, m)}, month{m}, year{y} {

unsigned int Date :: checkDay(unsigned int testDay, unsigned int testMonth) const {
    static const array<unsigned, monthsPerYear + 1> daysPerMonth{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (testDay <= daysPerMonth[testMonth] && testDay > 0) {
        return testDay;
    }
    return testDay;
}

或者在调用函数之前初始化month (您必须在month之前声明day然后),但我认为上面的解决方案有考虑到函数的作用,更好的对称性。我现在也考虑将checkDay成为static成员函数。

然后it should work reliably

当然,对于非学习计划,您将使用boost::gregorian::date。 :)

答案 1 :(得分:1)

initilization list order。类声明中变量的顺序决定了构造函数中赋值的顺序。只需在课程声明中 之前安排

private:
unsigned int month;
unsigned int day;