为什么没有参数标识符的函数在C ++中有效? [英] Why is a function without argument identifiers valid in C++?

查看:97
本文介绍了为什么没有参数标识符的函数在C ++中有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++中的一个函数作为参数,该参数只能是类型且没有标识符,

Given a function in C++ with arguments that are only types and have no identifiers,

 void foo1(int, int, int){cout << "called foo1";}

我可以这样称呼它:

int main()
{
    foo1(10, 10, 10);
}

为什么这在C ++中是有效的构造?这仅仅是C ++的特质,还是这种声明实际上有一定目的?我们真的可以访问以某种方式传递的参数吗? (这种方法声明在Java中不起作用.)

Why is this a valid construct in C++? Is this just an idiosyncrasy of C++, or does this kind of declaration actually have some purpose? Can we actually access the arguments that have been passed in somehow? (This kind of method declaration will not work in Java.)

推荐答案

考虑一种情况,要求您提供满足以下原型的功能

Consider a case where you are required to provide a function that meets the following prototype

void dostuff(int x, int y, int z);

并说您正在2D空间中操作,请勿在实现中使用z.你可以

And say you are operating in a 2D space and do not use z inside your implementation. You can

void dostuff(int x, int y, int z)
{
    // use x and y
}

并忽略z,但是编译器可能会发现您已定义但未使用z,并警告您可能会犯错.相反,您可以

and just ignore z, but the compiler will likely spot that you have defined but not used z and warn you that you could be making a mistake. Instead you can

void dostuff(int x, int y, int )
{
    // use x and y
}

,而忽略了z的定义.编译器将接受并静默丢弃第三个参数,因为它知道您不想要它.

and leave out the definition of z. The compiler will accept and silently discard the third parameter because it knows you don't want it.

由于这种错误,您不想简单地关闭警告

You do not want to simply turn off the warning because of errors like this

void dostuff(int x, int y, int z)
{
    for (int z = 0; z < MAX; z++)
    {
        // use x and y and z, the local z. 
    }
}

名称不正确的循环索引会遮盖参数z.现在将忽略呼叫者的输入,这可能会带来严重的后果.用标记1的眼球通常很难发现此错误,特别是如果局部z埋在复杂函数的深处.

Where a poorly-named loop index shadows the parameter z. The caller's input is now ignored and this could have bad consequences. This error is often hard to spot with the mark 1 eyeball, especially if the local z is buried somewhere deep in a complex function.

任何时候,编译器都能在您的代码中发现可能的错误,请利用.这对您来说意味着更少的工作.

Anytime the compiler can pick off a possible bug in your code, take advantage. It means less work for you.

这篇关于为什么没有参数标识符的函数在C ++中有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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