solidity:4.函数可见性与修饰符

一. 函数可见性

  • public - 支持内部或外部调用
  • private - 仅在当前合约调用,且不可被继承
  • internal- 只支持内部调用
  • external - 不支持内部调用
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract VisibilityA{

   uint public x;

   function t1() public pure returns(string memory) {
      return "public";
   }

   function t2() external pure returns(string memory) {
      return "external";
   }

    function t3() internal pure returns(string memory) {
      return "internal";
   }

    function t4() private pure returns(string memory) {
      return "private";
   }

    function t5() public view {
       t1();
       this.t2();  //可通过this调用外部函数
       t3();
       t4();
   }
}

contract VisibilityB is VisibilityA{
    function t6() public pure returns(string memory) {
       // t4(); private在继承时不可见
       // t2(); external在继承时不可见
       return t1();
    }

     function t7() public pure returns(string memory) {
        return t3();
    }
}

二. 函数修饰符

  • view - 表示该函数只读取而不修改状态变量
  • pure - 表示该函数既不读取也不修改状态变量
pragma solidity ^0.8.0;

contract ViewAndPure {
    uint x;

    function getA()public view returns(uint) {
       return x;
    } 

    function getB()public pure returns(uint) {
        return 3;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34793644/article/details/122359609