02.Solidity合約結構(初識別狀態變數、區域性變數、建構函式、解構函式)
阿新 • • 發佈:2018-12-19
1.什麼是合約?
在區塊鏈上執行的程式,通常稱為智慧合約(Smart Contract,所以通常會把寫區塊鏈程式改稱寫智慧合約。 合約就是執行在區塊鏈上的一段程式
完整合約
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;
狀態變數
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)銷燬當前合約