【Solidity】学习(3)

函数

重定义

不支持重定义,会在编译时候报错

pragma solidity ^0.4.0;

contract test {
    uint public a =100;
    function changeA () view returns(uint ){
        a = 700;
        return a;
    }
}

继承

  • 属性继承:public  internal 
  • 方法继承:public  internal  external
  • 继承重载
  • 多重继承按顺序,同名属性(方法)按最后一个为准,如果子合约自身有,覆盖其他

构造函数

在合约部署时候就自动执行

  • 使用合约同名的方法名,0.4版本
  • 直接使用constructor()函数
pragma solidity ^0.4.0;

contract test {
    address public add;
    constructor(){
    //合约部署之际就会将当前地址赋值给add
        add = msg.sender;
    }
}

 析构函数

kill合约

pragma solidity ^0.4.0;

contract father{
    address add;
    uint public a = 1;
    constructor (){
        add = msg.sender;
    }
    function ins() {
        a += 10;
    }
    //执行之后,再次点击a报错提示
    function kill(){
        if(add == msg.sender)
             selfdestruct(add);
    }
}

constant

  • 函数内部的constant在4.0版本中和view等价,在5.0版本中被废弃
  • 全局变量,constant变量,局部变量没有这个属性
  • 全局变量加上constant属性,就不能被修改

getter

  • public修饰符默认生产get方法,用于外部调用,不能在函数内部调用
    function get() external view returns(uint){
            return a;
        }
  • mapping特殊,会生成以下函数
        mapping(int =>string) map;
        function mapTest(int _a)  view returns(string){
            return map[_a];
        }

modifier

pragma solidity ^0.4.0;

contract test {
    uint public a;
    address public add;
    constructor(){
        add = msg.sender;
    }
    modifier OnlyAdd{
        require(add == msg.sender);
        _;
    }
    //首先会判断是否满足modifier中require的条件,如果满足则执行语句,不满足则回滚
    function changeA(uint _a) OnlyAdd{
        a = _a;
    } 
}

执行顺序(1)

pragma solidity ^0.4.0;

contract test {
    uint public a;
    modifier m1{
        a = 1;
        _;
        a = 2;
    }
    //讲_中的内容全部替换成changeA中的内容
    function changeA() m1{
        a = 100 ;
    }
}

执行顺序(2)

pragma solidity ^0.4.0;

contract test {
    uint public a;
    modifier m1{
        a = 1;
        _;
        a = 2;
    }
    modifier m2{
        a = 3;
        _;
        a = 4;
    }
    //执行顺序是,先遇到m1,执行a=1,接着将m2替换m1中的_
    //执行m2中的a=3,遇到_,用函数体替代之,执行完m2
    //最后执行m1中剩余部分
    function changeA() m1 m2{
        a = 100 ;
    }
}

猜你喜欢

转载自www.cnblogs.com/lhw-/p/10656842.html
今日推荐