数组参数的默认值 [英] Default values for array arguments

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

问题描述

只是用C ++打一点点。我真正想做的是能够使用为数组或指针参数定义的默认值来设置函数。为了保持简单,让我们使用一个数组。像这样:



void experimentA(char a [3] = {'a','b','c'}) code>



编译器(LLVM GCC 4.2 with GNU99)提示Expected expression。这是相当钝,但我被同事告诉这是发生,因为'值'我试图分配是静态分配,而变量我试图分配它( a [ 3] )是自动的。



但我不完全确定是否是这样,因为我可以这样做: / p>

void experimentB(char a [3] =abc);



编译器只是警告我字符串字面量到char *转换已被弃用。



我不明白为什么abc与{'a','b','c'}有根本的不同,以造成这种差异。

解决方案

您的同事错了,或者您误解了。



理解的第一个线索是你不能有一个数组作为C或C ++中的函数参数。原因是历史的。所以当你写 void experimentA(char a [3] ...)编译器会自动将其转换为指针,例如 void experimentA a ...)。所以真正的问题是为什么abc是a和 {'a','b','c'}的合适的默认值不是。原因是编译器解释,abc是一个表达式, {'a','b','c'} 不是(它的初始化器)。在C ++中有一些地方,你可以使用初始化器和一些你不能。参数的默认值恰好是您不能使用的地方之一。


Just playing around a little with C++. What I really want to do is to be able to setup a function with default values defined for an array or pointer argument. To keep things simple, let's just use an array. Like so:

void experimentA(char a[3] = {'a', 'b', 'c'});

The compiler (LLVM GCC 4.2 with GNU99) complains "Expected expression". That is quite obtuse, but I was told by colleagues that this is happening because the 'value' I'm trying to assign is statically allocated, whereas the variable I'm trying to assign it to (a[3]) is auto.

But I'm not completely sure if that's the case, since I'm able to do this:

void experimentB(char a[3] = "abc");

And the compiler merely warns me that string-literal to char* conversion is deprecated.

I don't understand how "abc" differs fundamentally from {'a','b','c'} in order to cause this discrepancy. Any insight is much appreciated!

解决方案

Your colleagues are wrong or maybe you misunderstood.

The first clue to understanding is that you cannot have an array as a function parameter in C or C++. The reasons are historical. So when you write void experimentA(char a[3] ...) the compiler automatically converts it to a pointer, i.e. void experimentA(char* a ...). So the real question is why "abc" is a suitable default value for a and { 'a', 'b', 'c' } is not. The reason is as the compiler explains, "abc" is an expression and { 'a', 'b', 'c' } is not (its an initialiser). There are some places in C++ where you can use an initialiser and some where you can't. Default value for a parameter just happens to be one of the places you can't.

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

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