Solidity 练习:可见性

2022-12-29 Web3 Solidity

# 一、题目说明

函数和状态变量必须声明它们是否可被其他合约访问。函数可以声明为:

  • public:可以由任何人和任何合约调用。
  • private:只能在合约内部调用。
  • internal:可以在合约和子合约内部调用。
  • external:只能从合约外部调用。

状态变量可以声明为 public、private 或 internal,但不能声明为 external。

# 二、任务列表

  • 在 VisibilityChild 中的函数 test 中,将 VisibilityChild 内部可以直接调用的所有状态变量和函数相加并返回总和。
  • 从总和中排除对 this.externalFunc() 的调用,因为不能直接在 test() 内部调用 externalFunc()。

# 三、解答代码

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

// visibility - public, private, internal, external
contract VisibilityBase {
    // State variables can be one of private, internal or public.
    uint private x = 0;
    uint internal y = 1;
    uint public z = 2;

    // Private function can only be called
    // - inside this contract
    // Contracts that inherit this contract cannot call this function.
    function privateFunc() private pure returns (uint) {
        return 0;
    }

    // Internal function can be called
    // - inside this contract
    // - inside contracts that inherit this contract
    function internalFunc() internal pure returns (uint) {
        return 100;
    }

    // Public functions can be called
    // - inside this contract
    // - inside contracts that inherit this contract
    // - by other contracts and accounts
    function publicFunc() public pure returns (uint) {
        return 200;
    }

    // External functions can only be called
    // - by other contracts and accounts
    function externalFunc() external pure returns (uint) {
        return 300;
    }

    function examples() external view {
        // Access state variables
        x + y + z;

        // Call functions, cannot call externalFunc()
        privateFunc();
        internalFunc();
        publicFunc();

        // Actually you can call an external function with this syntax.
        // This is bad code.
        // Instead of making an internal call to the function, it does an
        // external call into this contract. Hence using more gas than necessary.
        this.externalFunc();
    }
}

contract VisibilityChild is VisibilityBase {
    function examples2() external view {
        // Access state variables (internal and public)
        y + z;

        // Call functions (internal and public)
        internalFunc();
        publicFunc();
    }

    function test() external view returns (uint) {
        return y + z + internalFunc() + publicFunc();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

# 四、参考资料

Last Updated: 2023-01-28 4:31:25