找了好多资料,对使用const声明的参数介绍很少const 声明的参数是按值传递的,而且形参不能被改变。
---摘自《Delphi精要》71页有代码实例最好,看了Delphi里面的对值参与变参区别的代码,稍微理解了一些。谁能帮我理解一下const声明的参数有什么特性、用途?

解决方案 »

  1.   


    procedure Proc1(const Value: Integer);
    begin
      // 不能被赋值,编译不过
      //Value := 12;
    end;type
      TMyRec = record
        I1: Integer;
        I2: Integer;
      end;
    procedure Proc2(Value: TMyRec);
    begin
      // 因为Value不可赋值,所以编译骂会优化为按引用传递,而不是按值传递
      //Value.I1 := 20;
    end;
      

  2.   


    implementation
    const
      i = 10;
      

  3.   

    A constant (const) parameter is like a local constant or read-only variable. Constant parameters are similar to value parameters, except that you can't assign a value to a constant parameter within the body of a procedure or function, nor can you pass one as a var parameter to another routine. (But when you pass an object reference as a constant parameter, you can still modify the object's properties.)Using const allows the compiler to optimize code for structured- and string-type parameters. It also provides a safeguard against unintentionally passing a parameter by reference to another routine.Here, for example, is the header for the CompareStr function in the SysUtils unit:function CompareStr(const S1, S2: string): Integer;Because S1 and S2 are not modified in the body of CompareStr, they can be declared as constant parameters.