Solidity接口合约和抽象合约

Solidity接口合约和抽象合约

一、抽象合约

在solidity中,抽象合约指的是没有函数体的合约。

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.0 <0.9.0;

contract Abstract {
    function utterance() returns (bytes32);
    function bubbleSort(uint[] memory a) public pure virtual returns (uint[] memory); 
}

但是这样的合约不能通过编译,即使他们同时包含具体函数和抽象函数,但其他合约可以继承该抽象合约:

其中抽象函数要使用virtual关键字修饰,以便子合约重写。

另外如果一个合约是从抽象合约中继承的,但没有实现所有的函数,则他也是抽象合约。

二、接口合约

接口合约类似于抽象合约,但他们不能实现任何功能。接口的限制有如下:

  • 不能继承其他合约或接口

  • 不能定义构造函数

  • 不能定义状态变量

  • 函数可见性只能被external修饰,以外部调用方式调用

  • 不能定义结构体

  • 不能定义枚举变量

接口合约由interface关键字修饰

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.0 <0.9.0;

interface Toekn{
    event Transfer(address indexed from, address indexed to, uint amount);
    function transfer(address recipient, uint amount) external returns (bool);
}