Solidity – 抽象合约
抽象合约是具有至少一种函数但没有实现的合约。无法创建摘要的实例。抽象合约用作基础合约,以便子合约可以继承和利用其功能。抽象合约定义了合约的结构,从它继承的任何派生合约都应该为不完整的功能提供一个实现,如果派生合约也没有实现不完整的功能,那么该派生合约也将被标记为抽象。在 Solidity 中,没有用于创建抽象合约的 abstract 关键字,如果合约本身具有未实现的功能,它就会变成抽象的。
示例:在下面的示例中,创建了一个抽象合约,该合约被另一个实现了抽象合约所有功能的合约继承。在调用合约中创建抽象合约实例,并创建子合约对象。使用子合约的对象调用子合约中实现的所有抽象函数。
Solidity
// Solidity program to
// demonstrate
// Abstract contract
pragma solidity 0.4.19;
// Creating an abstract contract
contract abstractContract {
// Declaring functions
function getStr(
string _strIn) public view returns(
string memory);
function setValue(uint _in1, uint _in2) public;
function add() public returns(uint);
}
// Child contract inheriting
// an abstract parent
// contract 'abstractContract'
contract derivedContract is abstractContract{
// Declaring private
// variables
uint private num1;
uint private num2;
// Defining functions inherited
// from abstract parent contract
function getStr(
string _strIn) public view returns(
string memory){
return _strIn;
}
function setValue(
uint _in1, uint _in2) public{
num1 = _in1;
num2 = _in2;
}
function add() public returns(uint){
return (num2 + num1);
}
}
// Caller contract
contract call{
// Creating an instance of
// an abstract contract
abstractContract abs;
// Creating an object of
// child contract
function call(){
abs = new derivedContract();
}
// Calling functions inherited
// from abstract contract
function getValues(
) public returns (uint){
abs.setValue(10, 16);
abs.getStr("GeeksForGeeks");
return abs.add();
}
}
输出 :
在这里, abstractContract合约是一个抽象合约,它有一些没有实现的功能,而derivedContract是它的子合约。 getStr()和setValues()函数接受字符串和值,而add()函数添加setValues()函数的值。 abs是abstractContract的一个对象,它在调用合约中创建derivedContract的实例,该实例使用合约的变量并调用函数。