【问题标题】:Can main function have default argument values?主函数可以有默认参数值吗?
【发布时间】:2014-04-28 09:49:02
【问题描述】:

如何为main 函数参数设置默认值,如用户定义函数?

【问题讨论】:

  • 为什么需要这样做?
  • 你不能,如果你想使用某些值,你可以将它们存储在'main'中的一些局部变量中并使用它,就像你使用默认参数一样。
  • 这不是对上述问题的欺骗。在那里,OP 询问 argcargv 本身的使用,而这里将它们设置为默认值是问题。

标签: c++ arguments main default-value


【解决方案1】:

好吧,标准没有说明禁止 main 使用默认参数,并说您已成功合并编译器以同意您的这种情况

#include <iostream>

const char *defaults[] = { "abc", "efg" };

int main(int argc = 2, const char **argv = defaults)
{
    std::cout << argc << std::endl;
}

Live example。它编译时没有错误或警告,但它仍然没用;徒劳的实验。它几乎总是会打印1

每次调用程序时,例如,不带参数(或任何数量的参数),argc 被设置为 1argv[0] 指向程序名称,所以这样做是没有意义的,即这些变量永远不会保持不变,因此使用默认值几乎没有意义,因为默认值永远不会被使用。

因此,通常使用局部变量来实现这样的事情。像这样

int main(int argc, char **argv)
{
    int const default_argc = 2;
    char* const default_args[] = { "abc", "efg" };
    if (argc == 1)   // no arguments were passed
    {
       // do things for no arguments

       // usually those variables are set here for a generic flow onwards
       argc = default_argc;
       argv = default_args;
    }
}

【讨论】:

    【解决方案2】:

    我认为您想针对以下情况做两件不同的事情。

    1. 当没有参数被传递时
    2. 参数传递时。

    这是你的做法。

    int main(int argc, char *argv[]) 
    {
        if(argc == 1)
        {
            // case #1
        }
        else
        {
            // case #2
        }
    }
    

    【讨论】:

      【解决方案3】:

      使用 argc 和 argv?这些将从命令行将参数传递给您的程序。您不能真正使用默认参数。你必须在调用你的程序时像这样传递它们:

      $> ./my_addition "4" "7"
      
      
      
      int main(int argc, char *argv[]) 
      {
        // argc <=> 'argument count' (=3)
        // argv <=> 'argument vector' (i.e. argv[1] == "4")
        // argv[0] is usually the bin name, here "my_addition"
      
        for (int i = 0; i < argc; ++i)
          std::cout << argv[i] << std::endl;
        return (0);
      }
      

      也许您可以使用脚本来运行您的程序,这可能是最接近 main() 的默认参数的解决方案。

      exec_my_prog.sh:

      #!/bin/zsh
      call_your_program + very_meny_args
      

      调用./exec_my_prog.sh 将使用“默认”参数运行您的程序。

      【讨论】:

      • 是的,脚本是一种无需重新编译即可更改参数值的方法。还有其他方法吗?
      • 哼,恕我直言,没有。至少我不认识他们,我在谷歌上找不到他们。但我不是 C/C++ 奥术师,只是个学生))
      猜你喜欢
      • 2011-04-18
      • 2011-04-01
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 2012-09-13
      • 2023-02-25
      • 2012-07-25
      相关资源
      最近更新 更多