【问题标题】:C++ function-parameter default usageC++ 函数参数默认用法
【发布时间】:2013-11-09 17:21:39
【问题描述】:

我正在尝试理解参数默认设置,我让这段代码将 3 个参数传递给一个函数并返回产品。

我怎样才能使cout<<"3---... 和下面的“4---”行中的代码使用参数中的默认值?在底部查看我的输出

代码

            #include "stdafx.h"
            #include<iostream>

            using namespace std;

            int product(char str,int a=5, int b=2);

            int _tmain(int argc, _TCHAR* argv[])
            {



                cout<<"1---"<<product('A',40,50)<<endl;

                cout<<"2---"<<product('A')<<endl;
                cout<<"3---"<<product('A',NULL,50)<<endl;
                cout<<"4---"<<product('A',40)<<endl;

                int retValue=product('A',40,50);
                cout<<"5---"<<retValue<<endl;

                system("pause");
                return 0;
            }


            int product(char str,int a, int b){

                return(a*b);
            }

输出

1---2000

2---10

3---0

4---80

5---2000

按任意键继续。 . .

【问题讨论】:

  • 大喊真的有必要吗?标题本身就足够突出。
  • 我不明白 4 有什么问题,但 3 是不可能的,除非您编写另一个函数或使用类似 Boost 的命名参数。
  • @chris 我是怎么做到的?喊?我只是像输入 CODE 一样输入了 OUTPUT。归咎于“黑盒”转型。还是谢谢
  • 我指的不是这个。我指的是标题。

标签: c++ function parameter-passing


【解决方案1】:

我猜在案例 4 中,您希望值 40 成为第三个参数。无法使用函数默认参数来执行此操作,顺序就是它定义的顺序。但是,您可以覆盖该函数,以创建一个双参数版本,该版本使用正确的“默认”参数调用三参数函数:

int product(char str, int a, int b)
{
    ...
}

int product(char str, int b = 2)
{
    return product(str, 5, b);
}

对于上述函数,使用一个或两个参数调用,您调用最后一个函数,但如果您使用三个参数调用它,则调用第一个。

不幸的是,现在无法使用a 设置但将b 设置为上面的默认设置来调用。相反,您可以使用不同的命名函数,或者添加虚拟参数或检查例如获取参数的特殊值,或者您必须求助于像Boost parameter library 这样的“黑客”(正如克里斯所建议的那样)。

【讨论】:

    【解决方案2】:

    相关代码:

    int product(char str,int a=5, int b=2) { return a*b; }
    
        cout<<"3---"<<product('A',0,50);   // NULL stripped, it's for pointers
        cout<<"4---"<<product('A',40);
    

    给定所需的输出:

    3---0
    4---80
    

    如果 #3 的示例输出正确,则使用 a 的默认值会得到 250 而不是零。那你的样本输出错了吗?

    $ cat t.cpp
    #include <iostream>
    int product(char c, int a=5, int b=2) { return a*b; }
    int main (int c, char **v)
    {
        std::cout<<"3---"<<product('A',0,50)<<'\n';
        std::cout<<"4---"<<product('A',40)<<'\n';
    }
    $ make
    g++ -o bin/t -g -O   --std=gnu++11 -march=native -pipe -Wall -Wno-parentheses  t.cpp
    $ .bin/t
    bash: .bin/t: No such file or directory
    $ bin/t
    3---0
    4---80
    $ 
    

    【讨论】:

      猜你喜欢
      • 2014-07-09
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多