首页 > 解决方案 > 如何从外部将值传递给结构函数?

问题描述

我的代码中有一个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(){不知何故之后。您能否提供建议如何传递swtchst::print()

标签: c++structstaticparameter-passing

解决方案


试试下面

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

推荐阅读