c++ - 如何从外部将值传递给结构函数?
问题描述
我的代码中有一个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()
?
解决方案
试试下面
#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;
}
推荐阅读
- php - PHP中每5年从MySQL分组中动态选择输入
- r - 如何创建一个循环:将 4 个月的错误项相加,然后除以 r 中等效的 4 个月真实数字的总和?
- python - 盈透证券 TWS API 上的 IB Insync 期货订单问题
- php - 将 Ajax 与 php 站点一起使用
- javascript - 将幻灯片值的 ID 分配给变量
- angular - Angular 路由、国际化和部署
- delphi - Delphi:带有pdf文件的navigation2
- flutter - 在颤振中输入正确密码后如何关闭passCodeScreen
- regex - 将正则表达式转换为可在 Google 电子表格中使用的 re2?
- javascript - 致命错误:CALL_AND_RETRY_LAST 分配失败 - nginx 上的 JavaScript 堆内存不足