Solidity语言学习笔记————30、函数重载

函数重载(Function Overloading)

合约可以有多个同名但不同输入参数的函数。这也适用于继承的函数。下面示例展示了合约A中对函数f的重载。

pragma solidity ^0.4.16;

contract A {
    function f(uint _in) public pure returns (uint out) {
        out = 1;
    }

    function f(uint _in, bytes32 _key) public pure returns (uint out) {
        out = 2;
    }
}

在外部接口中也存在重载的函数。如果两个外部可见的函数的Solidity类型不同,但外部类型相同,不能成功重载。

// 下面代码无法编译
pragma solidity ^0.4.16;

contract A {
    function f(B _in) public pure returns (B out) {
        out = _in;
    }

    function f(address _in) public pure returns (address out) {
        out = _in;
    }
}

contract B {
}

以上两个f函数都接受了ABI的地址类型,虽然它们的Solidity类型不同。(合约类型相当于地址类型)

重载解析和参数匹配(Overload resolution and Argument matching)

通过将当前范围内的函数声明与函数调用中提供的参数相匹配,可以选择重载函数。如果所有参数都可以隐式地转换为预期类型,该函数则被选择作为重载候选项。如果没有一个候选,解析失败。

注解
返回参数没有考虑到重载解析。
pragma solidity ^0.4.16;

contract A {
    function f(uint8 _in) public pure returns (uint8 out) {
        out = _in;
    }

    function f(uint256 _in) public pure returns (uint256 out) {
        out = _in;
    }
}
Calling f(50) would create a type error since 250 can be implicitly converted both to uint8 and uint256 types. On another hand f(256) would resolve to f(uint256) overload as 256 cannot be implicitly converted to uint8. 
调用 f(50) 会有一个类型错误,因为 250 可以隐式地转换为 uint8 uint256 类型。另一方面, f(256) 将解析为 f(uint256) 重载,因为 256 不能隐式地转换为 uint8
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值