首页 > 解决方案 > 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(),它的打印效果就很好。为什么它会打印笑脸或俱乐部?

标签: c++initializationoutput

解决方案


中的+运算符"/" + 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();
}

推荐阅读