c++ - C ++调用返回成员函数输出“?初始化之前”
问题描述
当我运行这段代码时,我得到了这个输出。
主文件
#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()
,它的打印效果就很好。为什么它会打印笑脸或俱乐部?
解决方案
中的+
运算符"/" + GetDay()
and"/" + GetYear()
不是连接字符串,而是移动指向数组第一个元素"/"
( {'/', '\0'}
)的指针GetDay()
和GetYear()
前面的元素。
GetYear()
返回一个很大的值,因此指针会转到某个“随机”位置,并且before initialization
似乎恰好在那里。它应该在使用的库中的其他地方使用。
取而代之的是,您可以std::stringstream
像这样连接字符串和整数:
#include <sstream>
std::string Date::GetDate() const {
std::stringstream output;
output << GetMonth();
output << "/" << GetDay();
output << "/" << GetYear();
return output.str();
}
推荐阅读
- python - 为什么 max() 函数返回的项目小于列表中的另一个项目?
- plugins - 为 hippo cms 的 ckeditor 添加自定义颜色
- php - Laravel如何使用querybuilder从两列进行分组连接
- python - 文件上传 S3 和 heroku python
- kubernetes - 在 Openshift 上使用 Zookeeper
- c++ - 将枚举声明为循环边界
- email - 我如何从詹金斯管道多次发送电子邮件
- java - 如何在 Spring 表单中隐藏选项?
- awk - 如何在正常运行时间的输出中从右开始读取一行?
- java - StreamingResponseBody 抛出异常