简单的一行类方法返回错误的值

时间:2015-09-04 21:12:10

标签: c++ date inheritance output

我有一个奇怪的问题而且我不知道错误。

我有一个班级publication,由班级成员string headlinestring text组成。

我还有一个名为publication_and_date的类,它继承自publication,但还有一个名为string date的字段,表示某篇文章的发布日期。

我还有一个继承自news的课程publication_and_date,其附加字段为string sources

问题是:我有news类型的对象,当我使用该对象的方法get_date时,我得到值M

这是我的无效主要内容:

void main()
{
    news MyNews;

    MyNews.set_date(3,12,2016);
    MyNews.set_sources("IGN");
    MyNews.set_headline("MGS V wins GOTY award");
    MyNews.set_text("Metal Gear Solid V won the prestigious game of the year award!");

    cout << MyNews.ToString();
    getch();
}

这是类publication_and_date

的实现
publication_and_date::publication_and_date() : publication()
{
    date="1/9/2015";
}

void publication_and_date::set_date(const int NewDay,const int NewMonth,const int NewYear)
{
    if((NewDay > 31)||(NewDay < 1)||(NewMonth > 12)||(NewMonth < 1)||(NewYear<2015)) //input check
    {
        cout << "\nDate is invalid\n";
        return;
    }
    date=NewDay + '/' + NewMonth + '/' + NewYear;
}

string publication_and_date::get_date()
{
    return date;
}

如您所见,方法get_date()非常简单。它只是一行。

我不知道为什么我得到的价值是M

我给你的虚空主要的输出是:

Headline: MGS V wins GOTY award
Text: Metal Gear Solid V won the prestigious game of the year award!
Date: M
Sources: IGN

我完全不知道为什么会这样。非常感谢帮助。

Edit1:这是ToString的代码

string news::ToString()
{
    string ToReturn;
    ToReturn="\nHeadline: " + get_headline() + '\n' + "Text: " + get_text() + '\n'+"Date: " + get_date()+'\n'+"Sources: " + get_sources();
    return ToReturn;
}

EDIT2:

我想我知道问题所在。 NewDay, NewMonth,NewYear是整数。因此+运算符与字符串不同。我需要以某种方式让他们成为角色。

1 个答案:

答案 0 :(得分:2)

您正在获取M或其他随机内容,因为您将数字相加而不是连接字符串。 char '/'实际上是一个小整数,值为47.

将所有内容转换为字符串的一种方法是使用stringstream(位于sstream标头中):

std::stringstream ss;
ss << NewDay << '/' << NewMonth << '/' << NewYear;
date = ss.str();

字符串流就像常规的iostream一样,但它适用于字符串。关于类型转换,它会做正确的事情。