C++语法:缺省实参

函数调用的实参按位置解析 缺省实参只能用来替换函数调用缺少的尾部实参。
// 等价于 screenInit('<<', 80, ' ')

cursor = screenInit('<<");


// 错误, 不等价于 screenInit(24,80,'<<')

cursor = screenInit( , , '<<');


函数声明可以为全部或部分参数指定缺省实参, 在左边参数的任何缺省实参被提供之前, 最右边未初始化参数必须被提供缺省实参。 这是由于函数调用的实参是按照位置来解析的
// 错误: 在指定 height 之前, width 必须有一个缺省实参

char *screenInit( int height = 24, int width,char background = ' ' );


一个参数只能在一个文件中被指定一次缺省实参 例如 下列语句是错误的:
// ff.h
int ff( int = 0 );
// ff.C
#include "ff.h"
int ff( int i = 0 ) { ... } // error

      缺省实参在公共头文件包含的函数声明中指定 而不是在函数定义中 如果缺省实参在函数定义的参数表中提供 则缺省实参只能用在包含该函数定义的文本文件的函数调用中
已知下列在头文件 ff.h 中声明的函数声明:
int ff( int a, int b, int c = 0 ); // ff.h
  怎样重新声明 ff() 来把缺省实参提供给 b?下列语句是错误的,因为它重新指定了 c 的缺省实参
     #include "ff.h"

     int ff( int a, int b = 0, int c = 0 ); // 错误


(因为之前已经提供了int c 的默认值)

下列看起来错误的重新声明实际上是正确的
#include "ff.h"
int ff( int a, int b = 0, int c ); // ok
  在 ff()的重新声明中 b 是没有缺省实参的最右边参数。因此,缺省实参必须从最右边位置开始赋值的规则没有被打破 实际上,我们可以再次声明 ff()为
#include "ff.h"
int ff( int a, int b = 0, int c ); // ok

int ff( int a = 0, int b, int c ); // ok

缺省实参从最右边开始,不论数量是多少,都必须位于形参的最右边。


(待整理)

//LOOK AT THIS CODE
  1 #include    <iostream>
  2 #include    <vector>
  3 using   namespace std;
  4 typedef unsigned int opbit;
  5 void    test(int    a[5][])                                  //IF IT'S a[][5],IT WORKS WELL.
  6 {
  7     ;
  8 }
  9 int main()
 10 {
 11     int a[5][5];
 12     test(a);
 13     return  1;
 14 }
lichao@lichao:~/Projects/temp$ g++ test.cpp
test.cpp:5: 错误: declaration of ‘a’ as multidimensional array must have bounds for all dimensions except the first
test.cpp: In function ‘int main()’:
test.cpp:5: 错误: 给予 function ‘void test()’ 的实参太多

test.cpp:12: 错误: 在文件的这个地方


PS:还存在使用默认时如 test(int i = 0); 构造函数为test(); 

当使用test()时不知道该调用哪个的问题。

(待整理)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值