gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:20:40 25 4
gpt4 key购买 nike

我遇到了一个奇怪的问题,我不知道出了什么问题。

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

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

我还有一个继承自 publication_and_date 的类 news,并且有 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

我给你的void main的输出是:

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

编辑2:

我想我知道问题出在哪里了。 NewDay, NewMonth,NewYear 是整数。所以 + 运算符与字符串不同。我需要以某种方式使它们变成字符。

最佳答案

您得到一个 M 或其他随机数,因为您将数字相加而不是连接字符串。一个char '/'实际上是一个小整数,值为47。

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

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

字符串流就像您的常规 iostream,但它适用于字符串。它将在类型转换方面做正确的事情。

关于c++ - 简单的一行类方法返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32406670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com