合約函式的型別
Jul 27, 2017 · 3 min read
因為一直以來對於函式的型別不是很理解,加上看到有人分享解釋Parity錢包是因為沒加internal修飾詞導致後續被偷了很多錢,所以使用線上solidity IDE做了個簡單的實驗.
contract Test {
uint test = 0;
function testInternalFunc(uint _test) internal{
test = _test;
}
function testExternalFunc(uint _test) external{
test = _test;
}
function testPublicFunc(uint _test) public {
test = _test;
}
function testPrivateFunc(uint _test) private {
test = _test;
} function getTest() constant returns(uint){
return test;
}
}
在create完之後,有出現的function只有兩個
testExternalFunc
testPublicFunc
並且都可以直接呼叫函式改變state
接下來測試一下內部函式呼叫
function testFunc(uint _test) {
testInternalFunc(_test);
testExternalFunc(_test);
testPublicFunc(_test);
testPrivateFunc(_test);
}External函式會在compiler出現error
DeclarationError: Undeclared identifier
不過也可以前面加個this用this.testExternalFunc來呼叫
而剩下的三種都可以進行呼叫
接下來寫另一個合約
contract Test2 {
Test test = new Test();
function setTest(uint _test){
test.testInternalFunc(_test);
test.testExternalFunc(_test);
test.testPublicFunc(_test);
test.testPrivateFunc(_test);
}
function getTest() constant returns(uint){
return test.getTest();
}
}testInternalFunc / testPrivateFunc出現error
TypeError: Member “testInternalFunc” not found or not visible after argument-dependent lookup in contract Test.
接下來用繼承的方式
contract Test3 is Test{
function setTest(uint _test){
testInternalFunc(_test);
this.testExternalFunc(_test);
testPublicFunc(_test);
testPrivateFunc(_test);
}
}testPrivateFunc會在繼承的時候出現DeclarationError
所以大致上是如此,其實官方文件寫的也還滿清楚的,只是自己做一遍感覺又更深刻了一點.
2017.08.04 補充
在官方文件中定義了四種型別:external, public, internal, private
詳細文件請參考官方文件的Visibility and Getters

