【问题标题】:How do you declare functions with predefined arguments? [duplicate]如何声明带有预定义参数的函数? [复制]
【发布时间】:2021-12-15 00:48:21
【问题描述】:

我想知道你如何声明一个带有明确参数的函数。据说将函数声明放在开头,在 main() 函数之前,然后是它的定义是一种很好的做法,但在这种情况下,编译器会给我一个错误,因为它就像它没有看到正式的参数一样。

#include <iostream>
using namespace std;

void function(int i=1, char a='A', float val=45.7);

int main()
{
  function();
  return 0;
}

void function(int i = 1, char a='A', float val=45.7)
{
  cout << "i: " << i << endl;
  cout << "a: " << a << endl;
  cout << "val: " << val << endl;
}

我尝试在声明中插入形式参数,但它不起作用。

【问题讨论】:

    标签: c++


    【解决方案1】:

    您可以将预定义的参数放在前向声明中或在函数参数中,但不能 两者都

    如果你的函数有一个前向声明,你真的应该在前向声明中只有预定义的参数,不是 em> 在函数参数中。

    将其更改为:

    void function(int i, char a, float val)
    { 
         // you shouldn't use using namespace std;
         std::cout << "i: " << i << '\n'; // notice the use of newline character instead of std::endl
         std::cout << "a: " << a << '\n';
         std::cout << "val: " << val << '\n';
    }
    

    【讨论】:

      【解决方案2】:

      这里是将函数 args 初始化为默认值的方法。 您不需要在定义中传递默认参数。它们应该只在声明本身中给出。

      #include <iostream>
      using namespace std;
      
      void function(int i=1, char a='A', float val=45.7);
      
      int main()
      {
        function();
        return 0;
      }
      
      void function(int i, char a, float val)
      {
        cout << "i: " << i << endl;
        cout << "a: " << a << endl;
        cout << "val: " << val << endl;
      }
      

      现在,此代码将像魅力一样工作。 链接到工作示例 -> http://cpp.sh/4j7lx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-19
        • 2020-09-20
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多