- Solidity 教程
- Solidity - 首頁
- Solidity - 概述
- Solidity - 環境搭建
- Solidity - 基本語法
- Solidity - 第一個應用
- Solidity - 註釋
- Solidity - 資料型別
- Solidity - 變數
- Solidity - 變數作用域
- Solidity - 運算子
- Solidity - 迴圈
- Solidity - 條件判斷
- Solidity - 字串
- Solidity - 陣列
- Solidity - 列舉
- Solidity - 結構體
- Solidity - 對映
- Solidity - 型別轉換
- Solidity - 以太幣單位
- Solidity - 特殊變數
- Solidity - 樣式指南
- Solidity 函式
- Solidity - 函式
- Solidity - 函式修飾符
- Solidity - view 函式
- Solidity - pure 函式
- Solidity - 回退函式
- 函式過載
- 數學函式
- 加密函式
- Solidity 常用模式
- Solidity - 提款模式
- Solidity - 訪問限制
- Solidity 高階特性
- Solidity - 合約
- Solidity - 繼承
- Solidity - 建構函式
- Solidity - 抽象合約
- Solidity - 介面
- Solidity - 庫
- Solidity - 彙編
- Solidity - 事件
- Solidity - 錯誤處理
- Solidity 有用資源
- Solidity - 快速指南
- Solidity - 有用資源
- Solidity - 討論
Solidity - 合約
Solidity 中的合約類似於 C++ 中的類。合約具有以下屬性。
建構函式 − 使用 constructor 關鍵字宣告的特殊函式,每個合約只執行一次,在建立合約時呼叫。
狀態變數 − 每個合約的變數,用於儲存合約的狀態。
函式 − 每個合約的函式,可以修改狀態變數以改變合約的狀態。
可見性限定符
以下是合約函式/狀態變數的各種可見性限定符。
external − 外部函式旨在被其他合約呼叫。它們不能用於內部呼叫。要在合約內呼叫外部函式,需要使用 this.function_name() 呼叫。狀態變數不能標記為 external。
public − 公共函式/變數可以在外部和內部使用。對於公共狀態變數,Solidity 會自動建立一個 getter 函式。
internal − 內部函式/變數只能在內部或由派生合約使用。
private − 私有函式/變數只能在內部使用,即使是派生合約也不能使用。
示例
pragma solidity ^0.5.0;
contract C {
//private state variable
uint private data;
//public state variable
uint public info;
//constructor
constructor() public {
info = 10;
}
//private function
function increment(uint a) private pure returns(uint) { return a + 1; }
//public function
function updateData(uint a) public { data = a; }
function getData() public view returns(uint) { return data; }
function compute(uint a, uint b) internal pure returns (uint) { return a + b; }
}
//External Contract
contract D {
function readData() public returns(uint) {
C c = new C();
c.updateData(7);
return c.getData();
}
}
//Derived Contract
contract E is C {
uint private result;
C private c;
constructor() public {
c = new C();
}
function getComputedResult() public {
result = compute(3, 5);
}
function getResult() public view returns(uint) { return result; }
function getData() public view returns(uint) { return c.info(); }
}
使用Solidity 第一個應用章節中提供的步驟執行上述程式。執行合約的各種方法。對於 E.getComputedResult() 後跟 E.getResult() 顯示 -
輸出
0: uint256: 8
廣告