2. Solidity智能合约-构造函数与析构函数

本小节讨论Solidity的构造函数和析构函数

1. 把以下代码拷贝到 http://remix.ethereum.org/

其中标记蓝色的部分为构造函数,标记红色的部分为析构函数,与java中的一样,

构造函数主要用于初始化,析构函数主要用于销毁,在构造函数中初始化amount为90

pragma solidity ^0.4.13;
contract MyCoin{
    uint amount;
    address owner;
    
    function MyCoin() public{
        amount=90;
        owner=msg.sender;
    }

    
    function getBalance() public constant returns (uint){
        
        return amount;
        
    }
    
    function kill() public{
        if(owner==msg.sender){
            selfdestruct(owner);
        }
    }

}

2. 编译合约

参考上一小节

3. 构建合约实例

在Run选项中,点击create 构建合约实例

4. 调用合约方法

 点击第3步的getBalance,右边出现90,说明合约调用成功

5. 调用析构函数

点击kill,再次点击getBalance,会出现以下提示,说明合约对象已经销毁


作者:温春水  致力于研究区块链技术

微信:wencs1314  QQ群:612968783 

加群和微信,免费获得高质量区块链学习资料

猜你喜欢

转载自blog.csdn.net/tsyx/article/details/79497887
今日推荐