gpt4 book ai didi

c++ - 为什么我没有使用我类(class)的 toString 方法获得输出?

转载 作者:行者123 更新时间:2023-11-27 22:41:19 25 4
gpt4 key购买 nike

日期.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_ */

日期.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;
}

主要.cpp

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

using namespace std;

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

我在输出控制台中什么也得不到。

最佳答案

除了 一些程序员 识别的 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 before 调用函数(你也必须在 day 之前声明 month,然后)但我认为考虑到函数的作用,上面的解决方案具有更好的对称性。实际上,我现在也考虑将 checkDay 设为 static 成员函数。

然后 it should work reliably .

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

关于c++ - 为什么我没有使用我类(class)的 toString 方法获得输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48722518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com