函数调用默认参数 [英] function call with default parameter

查看:145
本文介绍了函数调用默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一篇关于C ++编程的考试。有一个问题,我和我的教授不同意。问题是,以下函数是否工作:

I wrote an examination about C++ programming. There was one question where I and my professor didn't agree. The question was, does the following function work or not:

#include <iostream>
using namespace std;

void f(int=4, long=10, double=3.14);

int main( int argc , char ** argv )
{
    f( , ,8);
      return EXIT_SUCCESS;
}

void f(int i, long l, double d) {
    cout << i << " " << " " << l << " " << d;
}

我说这不行,但我的教授说这一定会工作,因为的函数声明中的默认参数。我试过它与MSVC和它没有工作。是编译器特定的?

I said it would not work, but my professor said it will definitely work because of the default parameter in the function declaration. I tried it with MSVC and it didn't work. Is that compiler-specific? How can I convince my professor it doesn't work in any compiler, to raise my mark in the examination?

推荐答案

开始学习之前,我的教授不能在任何编译器中工作,与,你是对的,教授错了。事实上,他声称这应该工作(当它是微不足道,表明它不),意味着他可能不应该教C ++。但是如何显示他呢?

To begin with, you're right, the professor is wrong. And the fact that he claims that this should work (when it's trivial to show that it doesn't) means he probably shouldn't be teaching C++. But how to show him?

只需尝试使用至少两个不同的编译器编译它。如果两者都无法编译它,那么很有可能它是无效的代码。这是最快的方式。

Just try to compile it with at least two different compilers. If both fail to compile it, then there's a very good chance it's not valid code. That's the fastest way.

如果失败,引用C ++标准。下面是调用表达式的语法,如[expr.post] p1中所述,并遵循非终结引用:

If that fails, quote the C++ standard. Here's the syntax for a call expression, as described in [expr.post]p1 and following the non-terminal references:

postfix-expression:
    ...
    postfix-expression ( expression-list[opt] )

expression-list:
    initializer-list

initializer-list: ([dcl.init]p1)
    initializer-clause ...[opt]
    initializer-list , initializer-clause ...[opt]

initializer-clause:
    assignment-expression
    braced-init-list

braced-init-list:
    { initializer-list ,[opt] }
    { }



我不打算列出assignment-expression,不能永远不是什么,必须有至少一个令牌。这意味着一个初始化子句永远不会是什么,因此在函数参数中的逗号之间总是有一些东西。

I'm not going to list assignment-expression, but note that an expression cannot ever be nothing, there has to be at least one token. Which means that an initializer-clause can never be nothing, and thus there always has to be something between the commas in the function arguments.

这篇关于函数调用默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆