【发布时间】:2017-08-13 13:45:12
【问题描述】:
我是一个尝试边做边学的新手。我想将一个字符串流提供给一个名为“print()”的类成员函数,但我得到了错误。一旦这可行,我就可以继续编写更多类成员函数来处理我提供给它们的数据。
现在我已经创建了一个具有成员函数'print'的类。
class Month
{
public:
string m_month;
void print()
{
cout << m_month << endl;
}
};
接下来,我初始化了12个月:
Month month1 = { "January" };
Month month2 = { "February" };
Month month3 = { "March" };
etc.
当我调用“month1.print();”时它打印一月是正确的。
我使用 stringstream 和 for 循环将月份 + 1 连接到 12,我想将 stringstream 提供给 print 函数。
stringstream os;
string mValue = "month";
int iValue = 1;
for(int i = 0; i < 12; ++i)
{
os << mValue << "" << iValue << "\n";
iValue += 1;
}
但是,字符串流不能与打印功能结合使用。
os.print(); and os.str().print();
导致“错误:‘std::stringstream {aka class std::__cxx11::basic_stringstream}’没有名为‘print’的成员”
将 stringstream 转换为 char 然后将其输入 print 函数会导致“错误:在‘cstr’中请求成员‘print’,它是非类类型‘const char*’”
const string tmp = os.str();
const char* cstr = tmp.c_str();
cstr.print();
长话短说:我要做的是将月份 + 1 连接到 12 并将其提供给类成员函数“print”。这似乎微不足道,但我无法让它发挥作用。有什么建议么?
编辑:完整代码:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Month
{
public:
string m_month;
void print()
{
cout << m_month << endl;
}
};
int main()
{
Month month1 = { "January" };
Month month2 = { "February" };
Month month3 = { "March" };
Month month4 = { "April" };
Month month5 = { "May" };
Month month6 = { "June" };
Month month7 = { "July" };
Month month8 = { "August" };
Month month9 = { "September" };
Month month10 = { "October" };
Month month11 = { "November" };
Month month12 = { "December" };
stringstream os; // Initialize stringstream "os"
string mValue = "month"; // Initialize mValue "month"
int iValue = 1; // Initialize iValue "1"
for(int i = 0; i < 12; ++i)
{
os << mValue << "" << iValue << "\n"; // Glue mValue and iValue
// together
iValue += 1; // Increment iValue by one
}
send stringstream "os" to the print function // mock code: Here I want to send month1.print(); month2.print(); etc. to the print function. The output should be January, February etc.
return 0;
}
【问题讨论】:
-
很难理解你想用
os.print();做什么。正如错误所说, print 不是字符串流的方法。您是否打算将 stringstream 字符串分配给m_month?此外,您永远不会使用月份变量。我不确定你的 iValue 循环应该做什么。请澄清。 -
等等,你是不是想用 mValue for-loop 来获取月份对象?
-
我可能在这里没有使用正确的术语,但我所做的是创建了一个包含成员“m_month”和“print”的类。我已经将第 1 个月初始化为第 12 个月,所以当我调用“month1.print();”时它打印“一月”; 'month2.print();'打印“二月”等等。现在我希望程序打印“一月、二月、三月等”,而不必输入“month1.print();到month12.print();这就是 for 循环的用途。它递增并连接我想要输入打印功能的“month1 to 12”。我将在原帖中发布完整的代码。
-
你的“胶水”线是否真正成为月份变量?在您当前的代码中,您从不使用
month...变量。
标签: c++11 stringstream