代码之家  ›  专栏  ›  技术社区  ›  Nick Vanderbilt

通过引用传递,但引用数据而不是变量[关闭]

  •  0
  • Nick Vanderbilt  · 技术社区  · 15 年前

    这是psesudo代码。在哪种编程语言中这是可能的?

    def lab(input)
      input = ['90']
    end
    
    x = ['80']
    lab(x)
    
    puts x #=> value of x has changed from ['80'] to ['90]
    

    我用ruby写了这个,但是在ruby中我得到了最终的x值80 JavaScript也是如此。所以我想知道有没有

    4 回复  |  直到 13 年前
        1
  •  1
  •   Alex Martelli    15 年前

    有几种语言支持按引用传递:它在大多数Fortran版本中隐式存在的时间比大多数其他编程语言都要长 存在的 (有些版本前后使用副本,但最终结果最好相同;-),它由指定 var 在70年代的帕斯卡语中(虽然默认,如果你不说 变量 ,是复印件),等等。

    大多数现代语言(Java、Python、Ruby、Javascript、Go等)都是通过 对象 -引用(这就是你所说的“引用数据”),虽然有些更复杂,并且让你更精确地指定你想要的(例如,C++,C语言)。

        2
  •  1
  •   Mladen Jablanović    15 年前

    所以在Ruby中,你不能 x Array#replace 例如,在使用数组时可能很方便):

    def lab input
      input.replace ['90']
    end
    
    x = ['80']
    #=> ["80"]
    lab x
    #=> ["90"]
    x
    #=> ["90"]
    
        3
  •  1
  •   Kryptman    12 年前

    def lab(input, bnd)
      eval "#{input} = 90", bnd
    end
    
    x = 80
    lab("x", binding)
    

    更多信息请访问: http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc

        4
  •  0
  •   newacct    13 年前

    这在一种具有真正传递引用的语言中是可能的。

    public void lab(ref string[] input) {
      input = new string[] {"90"};
    }
    
    string[] x = {"80"};
    lab(x);
    

    菲律宾比索

    function lab(&$input) {
      $input = array('90');
    }
    
    $x = array('80');
    lab($x);
    

    void lab(string *&input) {
      input = new string[1];
      input[0] = "90";
    }
    
    string *x = new string[1];
    x[0] = "80";
    lab(x);
    

    sub lab {
      $_[0] = ['90'];
    }
    
    $x = ['80'];
    lab($x);
    
    推荐文章