【发布时间】:2021-05-15 04:39:10
【问题描述】:
当我运行这段代码时,我得到了这个输出。
main.cpp
#include <iostream>
#include "Date.h"
#include <string>
int main()
{
//Create
Date date = Date(1 , 1, 2000);
std::string str = date.GetDate();
std::cout << "Initial parameters: " << str << "\n";
//Use setters to change
date.SetDay(30);
date.SetMonth(5);
date.SetYear(1999);
std::cout << "Used setters: " << date.GetDate() << "\n";
//Input invalid parameters
date.SetDay(0);
date.SetMonth(13);
std::cout << "Set day to 0, month to 13: " << date.GetDate() << "\n";
}
日期.h
#ifndef DATE_H
#define DATE_H
#include <string>
class Date {
public:
Date(unsigned int, unsigned int, int);
void SetMonth(unsigned int);
void SetDay(unsigned int);
void SetYear(int);
std::string GetDate() const;
unsigned int GetMonth() const;
unsigned int GetDay() const;
int GetYear() const;
private:
unsigned int month{ 1 };
unsigned int day{ 1 };
int year{ 0 };
};
#endif
日期.cpp
#include "Date.h"
#include <string>
Date::Date(unsigned int month, unsigned int day, int year) {
SetMonth(month);
SetDay(day);
SetYear(year);
}
void Date::SetMonth(unsigned int month) {
if (month > 12 || month < 1) this->month = 1;
else this->month = month;
}
void Date::SetDay(unsigned int day) {
if (day < 1) this->day = 1;
else this->day = day; //TODO upper day limit (not for this exercise though hahahahaaaa)
}
void Date::SetYear(int year) {
this->year = year;
}
std::string Date::GetDate() const {
std::string output;
output = GetMonth();
output += "/" + GetDay();
output += "/" + GetYear();
return output;
}
unsigned int Date::GetMonth() const { return month; }
unsigned int Date::GetDay() const { return day; }
int Date::GetYear() const { return year; }
TLDR main.cpp 第 12、18 和 23 行在我的自定义 Date 类的对象上调用成员函数 GetDate() - 原型化 Date.h 第 12 行并定义 Date.cpp 第 24 行。它不是输出它应该输出的东西,而是输出“?初始化之前”。
代替date.GetDate(),它会打印“?初始化之前”。 什么在初始化之前?功能?成员字段全部初始化。事实上,如果我调用并输出只是其中一个成员字段,例如std::cout << date.GetDay(),它会打印得很好。为什么要打印笑脸或俱乐部?
【问题讨论】:
-
output += "/" + GetDay();是可疑行。 operator precedence 可以扩展为output += ("/" + GetDay());。这意味着我对这个编译感到惊讶,我不希望+甚至可以为const char[2]和unsigned int工作。 ETA:指针算法!当然。
标签: c++ initialization output