LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 2367|回复: 5

About default arguments

[复制链接]
发表于 2003-8-29 23:26:08 | 显示全部楼层 |阅读模式
From http://www.kuzbass.ru:8086/docs/isocpp/decl.html#dcl.fct

A default argument expression is implicitly converted (clause conv) to the parameter type. The default argument expression has the same semantic constraints as the initializer expression in a declaration of a variable of the parameter type, using the copy-initialization semantics (dcl.init). The names in the expression are bound, and the semantic constraints are checked, at the point where the default argument expression appears. Name lookup and checking of semantic constraints for default arguments in function templates and in member functions of class templates are performed as described in temp.inst. [Example: in the following code, g will be called with the value f(1):

  1. int a = 1;
  2. int f(int);
  3. int g(int x = f(a));            //  default argument:  f(::a)

  4. void h() {
  5.     a = 2;
  6.     {
  7.         int a = 3;
  8.         g();                    //   g(f(::a))
  9.     }
  10. }


  11. --- end example]
复制代码


In my experiment with following code:

  1. #include<iostream>
  2. using namespace std;

  3. int a = 1;
  4. int f(int);
  5. int g(int x = f(a));            //  default argument:  f(::a)

  6. int f(int i)
  7. {
  8.         return i;
  9. }
  10. void
  11. h()
  12. {
  13.     a = 2;
  14.     {
  15.         int a = 3;
  16.         g();                    //   g(f(::a))
  17.     }
  18. }

  19. int
  20. g(int x)
  21. {
  22.         cout << "x is " << x << endl;
  23. }

  24. int
  25. main ()
  26. {
  27.         h();
  28. }
复制代码


The result is:
x is 2
this shows that the default argument is f(2) but not f(1), for 'a' has been modified in function 'int h()'. Is it right?
发表于 2003-8-29 23:50:52 | 显示全部楼层
对呀!
void
h()
{
    a = 2; // 这里已经给a赋值为2了
……
发表于 2003-8-30 00:04:19 | 显示全部楼层
我怎么觉得好像应该是 3 吧,因为最内层的 a 定义应该覆盖外面的 a 的定义吧
 楼主| 发表于 2003-8-30 00:11:06 | 显示全部楼层
The names in the expression are bound, and the semantic constraints are checked, at the point where the default argument expression appears
这句应该是说表达式是使用默认参数第一次出现时的。
所以x=f(a),中的a应该是全局变量a,而这个a在h中改变了,所以不是1,而是2.
发表于 2003-8-30 18:59:03 | 显示全部楼层
I c, thanks
发表于 2003-8-30 19:50:55 | 显示全部楼层
呵呵,迷惑人的问题。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表