一个完整的合约
一个完整的合约,我们可以理解为一个类,代码如下:
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
相当于其他语言中的class
,Counter
相当于类名
,contract Counter相当于class Counter extends Contract。
状态变量
uint count = 0;
address owner;
count
和owner
就是状态变量,合约中的状态变量
相当于类中的属性变量
。
构造函数(Contructor)
function Counter()函数名和合约名相同时,此函数是合约的构造函数
,当合约对象创建时,会先调用构造函数对相关数据进行初始化处理。
成员函数
function increment() public
和function 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)
销毁当前合约。