Solidity基础入门知识(三)字符串和函数

字符串:需要使用双引号“”或者单引号’’括起来,例如:定义一个字符串变量:string  name=“jake”;

string字符串不能通过length方法获得长度

十六进制数据以关键字hex打头,后面紧跟用单或双引号包裹的字符串。如hex"001122ff"。通过下面的例子来理解下是什么意思:

contract HexLiteral{
    function test() returns (string){
      var a = hex"001122FF";

      //var b = hex"A";
      //Expected primary expression
      
      return a;
  }
}

由于一个字节是8位,所以一个hex是由两个[0-9a-z]字符组成的。所以var b = hex"A";不是成双的字符串是会报错的。var类型会在后面的文章进行解释。

十六进制的字面量与字符串可以进行同样的类似操作(例如索引):

pragma solidity ^0.4.0;

contract HexLiteralBytes{
    function test() returns (bytes4, bytes1, bytes1, bytes1, bytes1){
      bytes4 a = hex"001122FF";

      return (a, a[0], a[1], a[2], a[3]);
  }
}

可以发现,它可以隐式的转为bytes,上述代码的执行结果如下:

Result: "0x001122ff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011000000000000000000000000000000000000000000000000000000000000002200000000000000000000000000000000000000000000000000000000000000ff00000000000000000000000000000000000000000000000000000000000000"
Transaction cost: 21857 gas. 
Execution cost: 585 gas.
Decoded: 
bytes4: 0x001122ff
bytes1: 0x00
bytes1: 0x11
bytes1: 0x22
bytes1: 0xff

函数(function):函数有两种类型,内部函数(internal)和外部函数(external),内部函数只能在当前合约的上下文内使用,外部函数允许使用到本合约之外的地方。函数的默认类型是内部函数,如果外部函数被本合约之外的环境调用,会自动转换为bytes24类型,包括20字节的函数所在地址和4字节的函数方法签名。

例子:function abc(uint a) returns(uint){

                 return a;       

          }

abc是函数名字,括号内是参数,如果没有参数则括号内为空,returns是返回值,需要在括号内定义好返回值的类型,如果没有返回值,则必须省略returns关键字。

通过一个例子来学习更多的变化情况:

contract FuntionTest{
    function internalFunc() internal{}

    function externalFunc() external{}

    function callFunc(){
        //直接使用内部的方式调用
        internalFunc();

        //不能在内部调用一个外部函数,会报编译错误。
        //externalFunc();
        //Error: Undeclared identifier.

        //不能通过`external`的方式调用一个`internal`
        //Member "internalFunc" not found or not visible after argument-dependent lookup in contract FuntionTest
        //this.internalFunc();

        //使用`this`以`external`的方式调用一个外部函数
        this.externalFunc();
    }
}
contract FunctionTest1{
    function externalCall(FuntionTest ft){
        //调用另一个合约的外部函数
        ft.externalFunc();
        
        //不能调用另一个合约的内部函数
        //Error: Member "internalFunc" not found or not visible after argument-dependent lookup in contract FuntionTest
        //ft.internalFunc();
    }
}

解释:函数internalFunc被定义为内部函数,可以直接调用。函数externalFunc被定义为外部函数,在本合约内直接调用会报错,需要加上关键字this:this.externalFunc( )才可以。同时,在内部函数前加this函数会报错,不能用外部函数的调用方法来调用内部函数。

调用另一个合约的外部函数格式:ft.externalFunc( ),   fx是另一个合约的名字,externalFunc是外部函数的名字。另一个合约的内部函数是不能被调用的,会报错。










猜你喜欢

转载自blog.csdn.net/aaa19890808/article/details/79332833