C++调用return成员函数输出“?before initialization”

C++ Calling return member function outputs "?before initialization"

当我 运行 这段代码时,我得到了这个输出。

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";
}

Date.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

Date.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 行调用成员函数 GetDate() - 原型 Date.h 第 12 行并定义 Date.cpp 第 24 行 - on我的自定义日期 class 的一个对象。它没有输出它应该输出的内容,而是输出“?在初始化之前”。

代替 date.GetDate() 它打印“?before initialization”。 初始化之前是什么?功能?成员字段全部初始化。事实上,如果我调用并输出 just 成员字段之一,例如 std::cout << date.GetDay(),它打印得很好。为什么它打印笑脸或俱乐部?

"/" + GetDay()"/" + GetYear()中的+运算符不是连接字符串而是移动指向数组第一个元素的指针"/"{'/', '[=15= ]'}) GetDay()GetYear() 前面的元素。

GetYear() returns 一个很大的值,所以指针指向某个“随机”位置并且 before initialization 似乎恰好在那里。它应该在所用库的其他地方使用。

除此之外,您可以使用 std::stringstream 连接字符串和整数,如下所示:

#include <sstream>

std::string Date::GetDate() const {
    std::stringstream output;
    output << GetMonth();
    output << "/" << GetDay();
    output << "/" << GetYear();
    return output.str();
}