【发布时间】:2019-12-13 20:54:11
【问题描述】:
在我的代码中定义了一个struct,我想从“外部”传递一个值。下面是这个问题的一个例子:
#include <iostream>
#include <string>
using namespace std;
int main()
{
struct st
{
static void print(int a, int b)
{
string swtch = "+";
if (swtch == "+")
{
cout << a + b << endl;
}
else if (swtch == "-")
{
cout << a - b << endl;
}
else
{
cout <<
"Warning: This case is not implemented." << endl;
system("pause");
exit(0);
}
}
};
st::print(1,2);
return 0;
}
将语句string swtch = "+"; 移到结构st 之外会很有用(例如,就在int main(){之后。您能否提供建议,然后如何将swtch 传递给st::print()?
【问题讨论】:
-
为什么不作为附加参数传递?一个简单的
char还不够(而不是更复杂的std::string)? -
一般建议:
system("pause");在控制台程序中是相当糟糕的主意。保持某些控制台窗口打开不是应用程序的任务,在最坏的情况下,这会阻止应用程序从某个脚本内部运行。相反,您可以显式打开控制台并从内部运行您的程序。 -
你不需要“结构”,这只是分散注意力。
-
这只是一个例子,实际任务与问题中提出的不同。
标签: c++ struct static parameter-passing