区块链:Solidity合约结构

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wtdask/article/details/81945422

一个完整的合约

一个完整的合约,我们可以理解为一个类,代码如下:

pragma solidity ^0.4.4;

contract Counter {

    uint count = 0;
    address owner;

    function Counter() {
       owner = msg.sender;
    } 

    function increment() public {
       uint step = 10;
       if (owner == msg.sender) {
          count = count + step;
       }
    }

    function getCount() constant returns (uint) {
       return count;
    }

    function kill() {
       if (owner == msg.sender) { 
          selfdestruct(owner);
       }
    }
}

版本声明

pragma solidity ^0.4.4;

pragma solidity代表solidity版本声明0.4.4代表solidity版本^表示向上兼容^0.4.4表示solidity的版本在0.4.4 ~ 0.5.0(不包含0.5.0)的版本都可以对上面的合约代码进行编译,0.4.5,0.4.8等等可以用来修复前面的solidity存在的一些bug。

合约声明

contract是合约声明的关键字,Counter是合约名字,contract Counter就是声明一个Counter合约

contract相当于其他语言中的classCounter相当于类名,contract Counter相当于class Counter extends Contract。

状态变量

uint count = 0;
address owner;

countowner就是状态变量,合约中的状态变量相当于类中的属性变量

构造函数(Contructor)

function Counter()函数名和合约名相同时,此函数是合约的构造函数,当合约对象创建时,会先调用构造函数对相关数据进行初始化处理。

成员函数

function increment() publicfunction getCount() constant returns (uint)都是Counter合约的成员函数,成员函数在iOS里面叫做方法、行为,合约实例可以调用成员函数处理相关操作。当调用increment()函数时,会让状态变量count增加step。当调用getCount()时会得到状态变量count的值。

本地变量

function increment() public {
   uint step = 10;
   if (owner == msg.sender) {
      count = count + step;
   }
}

increment()方法中声明的step就是局部变量。局部变量只在离它最近的{}内容使用。

析构函数(selfdestruct)

析构函数构造函数对应构造函数是初始化数据,而析构函数是销毁数据。在counter合约中,当我们手动调用kill函数时,就会调用selfdestruct(owner)销毁当前合约。

猜你喜欢

转载自blog.csdn.net/wtdask/article/details/81945422