【发布时间】:2012-05-04 11:15:17
【问题描述】:
当前源代码:
string itoa(int i)
{
std::string s;
std::stringstream out;
out << i;
s = out.str();
return s;
}
class Gregorian
{
public:
string month;
int day;
int year; //negative for BC, positive for AD
// month day, year
Gregorian(string newmonth, int newday, int newyear)
{
month = newmonth;
day = newday;
year = newyear;
}
string twoString()
{
return month + " " + itoa(day) + ", " + itoa(year);
}
};
在我的主要:
Gregorian date = new Gregorian("June", 5, 1991);
cout << date.twoString();
我收到此错误:
mayan.cc: In function ‘int main(int, char**)’:
mayan.cc:109:51: error: conversion from ‘Gregorian*’ to non-scalar type ‘Gregorian’ requested
有谁知道为什么 int 到字符串的转换在这里失败?我对 C++ 相当陌生,但对 Java 很熟悉,我花了很多时间寻找这个问题的直接答案,但目前很难过。
【问题讨论】:
-
您可以在
itoa中删除std::string s;,而只删除return out.str();。返回字符串将在 stringstream 被销毁之前构造。合理的编译器可能会在这两种情况下生成完全相同的代码,但额外的临时代码往往会向查看您的代码的人暗示您不理解或不信任 C++ 范围规则。 -
不相关,但您的意思是将函数命名为
toString()? -
来自 Java,我不知道 C++ 是否已经有了 toString() 方法。如果不需要,我不想超载它。
标签: c++ string int type-conversion